Commit e6f607d3 authored by hewei's avatar hewei

CommentPlugin的测试用例

parent d70d056e
......@@ -12,4 +12,4 @@
hs_err_pid*
.idea/
mybatis-generator-plugin.iml
target/
\ No newline at end of file
target/
......@@ -63,6 +63,7 @@ public class TemplateCommentGenerator implements CommentGenerator {
if (useForDefault){
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(templatePath);
doc = new SAXReader().read(inputStream);
inputStream.close();
} else {
File file = new File(templatePath);
if (file.exists()) {
......
......@@ -16,6 +16,27 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.tools.DBHelper;
import com.itfsw.mybatis.generator.plugins.tools.MyBatisGeneratorTool;
import com.itfsw.mybatis.generator.plugins.tools.ObjectUtil;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.Element;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* ---------------------------------------------------------------------------
*
......@@ -25,4 +46,63 @@ package com.itfsw.mybatis.generator.plugins;
* ---------------------------------------------------------------------------
*/
public class CommentPluginTest {
/**
* 初始化
*/
@BeforeClass
public static void init() throws Exception {
DBHelper.createDB("scripts/ComentPlugin/init.sql");
}
/**
* 测试没有配置模板的情况
*/
@Test
public void testGenerateWithoutTemplate() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ComentPlugin/mybatis-generator-without-template.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
// 是否在使用系统默认模板
int count = 0;
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
if (file.getFormattedContent().indexOf("@project https://github.com/itfsw/mybatis-generator-plugin") != -1) {
count++;
}
}
Assert.assertTrue(count > 0);
}
/**
* 测试配置了模板参数转换
*/
@Test
public void testGenerateWithTemplate() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ComentPlugin/mybatis-generator.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
// java中的注释
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
if (file.getFileName().equals("Tb.java")) {
TopLevelClass topLevelClass = (TopLevelClass) file.getCompilationUnit();
// addJavaFileComment
Assert.assertEquals(topLevelClass.getFileCommentLines().get(0), "TestAddJavaFileComment:Tb:" + new SimpleDateFormat("yyyy-MM").format(new Date()));
// addFieldComment 同时测试 if 判断和 mbg
Field id = topLevelClass.getFields().get(0);
Assert.assertEquals(id.getJavaDocLines().get(0), "注释1");
Assert.assertEquals(id.getJavaDocLines().get(1), MergeConstants.NEW_ELEMENT_TAG);
// addGeneralMethodComment
Method cons = topLevelClass.getMethods().get(0);
Assert.assertEquals(cons.getJavaDocLines().get(0), "addGeneralMethodComment:Tb:tb");
// addSetterComment
Method setter = topLevelClass.getMethods().get(5);
Assert.assertEquals(setter.getJavaDocLines().get(0), "addSetterComment:field1:field1");
}
}
// xml注释
ObjectUtil xml = new ObjectUtil(myBatisGenerator.getGeneratedXmlFiles().get(0));
Document doc = (Document) xml.get("document");
List<Element> els = ((XmlElement) (doc.getRootElement().getElements().get(0))).getElements();
String comment = ((TextElement) els.get(0)).getContent();
Assert.assertEquals(comment, "addComment:BaseResultMap");
}
}
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50617
Source Host : localhost:3306
Source Database : mybatis-generator-plugin
Target Server Type : MYSQL
Target Server Version : 50617
File Encoding : 65001
Date: 2017-06-26 17:30:13
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb
-- ----------------------------
DROP TABLE IF EXISTS `tb`;
CREATE TABLE `tb` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
PRIMARY KEY (`id`)
);
-- ----------------------------
-- Records of tb
-- ----------------------------
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2017.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="db.properties"/>
<!--导入属性配置 -->
<context id="default" targetRuntime="MyBatis3">
<!-- 插件 -->
<!-- 注释插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.CommentPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin" />
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject="">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 给Model添加一个父类 -->
<!--<property name="rootClass" value="com.itfsw.base"/>-->
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="" targetProject="" />
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<table tableName="tb">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2017.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="db.properties"/>
<!--导入属性配置 -->
<context id="default" targetRuntime="MyBatis3">
<!-- 插件 -->
<!-- 注释插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.CommentPlugin">
<property name="template" value="src/test/resources/scripts/ComentPlugin/test-comment.ftl"/>
</plugin>
<plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin" />
<commentGenerator>
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject="">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 给Model添加一个父类 -->
<!--<property name="rootClass" value="com.itfsw.base"/>-->
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="" targetProject="" />
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<table tableName="tb">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<template>
<!-- #############################################################################################################
/**
* This method is called to add a file level comment to a generated java file. This method could be used to add a
* general file comment (such as a copyright notice). However, note that the Java file merge function in Eclipse
* does not deal with this comment. If you run the generator repeatedly, you will only retain the comment from the
* initial run.
* <p>
*
* The default implementation does nothing.
*
* @param compilationUnit
* the compilation unit
*/
-->
<comment ID="addJavaFileComment"><![CDATA[
TestAddJavaFileComment:${compilationUnit.type.shortName}:${.now?string("yyyy-MM")}
]]></comment>
<!-- #############################################################################################################
/**
* This method should add a suitable comment as a child element of the specified xmlElement to warn users that the
* element was generated and is subject to regeneration.
*
* @param xmlElement
* the xml element
*/
-->
<comment ID="addComment"><![CDATA[
addComment:${xmlElement.attributes[0].value}
]]></comment>
<!-- #############################################################################################################
/**
* This method is called to add a comment as the first child of the root element. This method could be used to add a
* general file comment (such as a copyright notice). However, note that the XML file merge function does not deal
* with this comment. If you run the generator repeatedly, you will only retain the comment from the initial run.
* <p>
*
* The default implementation does nothing.
*
* @param rootElement
* the root element
*/
-->
<comment ID="addRootComment"></comment>
<!-- #############################################################################################################
/**
* This method should add a Javadoc comment to the specified field. The field is related to the specified table and
* is used to hold the value of the specified column.
* <p>
*
* <b>Important:</b> This method should add a the nonstandard JavaDoc tag "@mbg.generated" to the comment. Without
* this tag, the Eclipse based Java merge feature will fail.
*
* @param field
* the field
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
-->
<comment ID="addFieldComment"><![CDATA[
<#if introspectedColumn??>
<#if introspectedColumn.remarks?? && introspectedColumn.remarks != ''>
<#list introspectedColumn.remarks?split("\n") as remark>
${remark}
</#list>
</#if>
${mgb}
</#if>
]]></comment>
<!-- #############################################################################################################
/**
* Adds a comment for a model class. The Java code merger should
* be notified not to delete the entire class in case any manual
* changes have been made. So this method will always use the
* "do not delete" annotation.
*
* Because of difficulties with the Java file merger, the default implementation
* of this method should NOT add comments. Comments should only be added if
* specifically requested by the user (for example, by enabling table remark comments).
*
* @param topLevelClass
* the top level class
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addModelClassComment"><![CDATA[
/**
<#if introspectedTable.remarks?? && introspectedTable.remarks != ''>
* Database Table Remarks:
<#list introspectedTable.remarks?split("\n") as remark>
* ${remark}
</#list>
</#if>
*
* This class was generated by MyBatis Generator.
* This class corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb} do_not_delete_during_merge
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the inner class comment.
*
* @param innerClass
* the inner class
* @param introspectedTable
* the introspected table
* @param markAsDoNotDelete
* the mark as do not delete
*/
-->
<comment ID="addClassComment"><![CDATA[
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}<#if markAsDoNotDelete?? && markAsDoNotDelete> do_not_delete_during_merge</#if>
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the enum comment.
*
* @param innerEnum
* the inner enum
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addEnumComment"><![CDATA[
/**
* This enum was generated by MyBatis Generator.
* This enum corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the interface comment.
*
* @param innerInterface
* the inner interface
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addInterfaceComment"><![CDATA[
/**
* This interface was generated by MyBatis Generator.
* This interface corresponds to the database table ${introspectedTable.fullyQualifiedTable}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
]]></comment>
<!-- #############################################################################################################
/**
* Adds the getter comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
-->
<comment ID="addGetterComment"><![CDATA[
<#if introspectedColumn??>
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* @return the value of ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
<#else>
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the field ${method.name?replace("get","")?replace("is", "")?uncap_first}
*
* @return the value of field ${method.name?replace("get","")?replace("is", "")?uncap_first}
*
* ${mgb}
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
</#if>
]]></comment>
<!-- #############################################################################################################
/**
* Adds the setter comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
* @param introspectedColumn
* the introspected column
*/
-->
<comment ID="addSetterComment"><![CDATA[
addSetterComment:${method.name?replace("set","")?uncap_first}:${method.parameters[0].name}
]]></comment>
<!-- #############################################################################################################
/**
* Adds the general method comment.
*
* @param method
* the method
* @param introspectedTable
* the introspected table
*/
-->
<comment ID="addGeneralMethodComment"><![CDATA[
addGeneralMethodComment:${method.name}:${introspectedTable.fullyQualifiedTable}
]]></comment>
</template>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment