生成单元测试代码.

This commit is contained in:
lijiahang
2023-08-24 19:14:27 +08:00
parent de4569890f
commit 58901b5903
14 changed files with 292 additions and 110 deletions

View File

@@ -15,11 +15,11 @@ import org.hibernate.validator.constraints.Range;
@Data
public class PageRequest implements IPageRequest {
@Range(min = 1, max = 10000)
@Range(min = 1, max = 10000, groups = IPageRequest.class)
@Schema(description = "页码")
private int page;
@Range(min = 1, max = 100)
@Range(min = 1, max = 100, groups = IPageRequest.class)
@Schema(description = "大小")
private int limit;

View File

@@ -42,7 +42,7 @@ public class BaseDO implements Serializable {
*/
@TableLogic
@Schema(description = "是否删除 0未删除 1已删除")
@TableField(fill = FieldFill.INSERT, jdbcType = JdbcType.BIT)
@TableField(fill = FieldFill.INSERT, jdbcType = JdbcType.TINYINT)
private Boolean deleted;
}

View File

@@ -9,6 +9,7 @@ import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.orion.lang.constant.Const;
import com.orion.lang.utils.ansi.AnsiColor;
import com.orion.lang.utils.ext.yml.YmlExt;
import com.orion.ops.framework.mybatis.core.domain.BaseDO;
import com.orion.ops.framework.mybatis.core.mapper.IMapper;
@@ -41,7 +42,7 @@ public class CodeGenerator {
// new GenTable("system_user", "用户", "user")
// .vue("user", "user")
// .enums(UserStatusEnum.class),
new GenTable("favorite", "收藏", "favorite", true),
new GenTable("favorite", "收藏", "favorite"),
};
// jdbc 配置 - 使用配置文件
File yamlFile = new File("orion-ops-launch/src/main/resources/application-dev.yaml");
@@ -102,6 +103,9 @@ public class CodeGenerator {
// 执行
ag.execute(engine);
// 打印提示信息
printTips();
}
/**
@@ -286,54 +290,57 @@ public class CodeGenerator {
*/
private static InjectionConfig getInjectionConfig() {
String[][] customFileDefineArr = new String[][]{
// -------------------- 后端 - service --------------------
// -------------------- 后端 - module --------------------
// http 文件
new String[]{"/templates/orion-server-module-controller.http.vm", "%sController.http", "controller"},
new String[]{"/templates/orion-server-module-controller.http.vm", "${type}Controller.http", "controller"},
// vo 文件
new String[]{"/templates/orion-server-module-entity-vo.java.vm", "%sVO.java", "entity.vo"},
new String[]{"/templates/orion-server-module-entity-vo.java.vm", "${type}VO.java", "entity.vo"},
// create request 文件
new String[]{"/templates/orion-server-module-entity-request-create.java.vm", "%sCreateRequest.java", "entity.request.%s"},
new String[]{"/templates/orion-server-module-entity-request-create.java.vm", "${type}CreateRequest.java", "entity.request.${bizPackage}"},
// update request 文件
new String[]{"/templates/orion-server-module-entity-request-update.java.vm", "%sUpdateRequest.java", "entity.request.%s"},
new String[]{"/templates/orion-server-module-entity-request-update.java.vm", "${type}UpdateRequest.java", "entity.request.${bizPackage}"},
// query request 文件
new String[]{"/templates/orion-server-module-entity-request-query.java.vm", "%sQueryRequest.java", "entity.request.%s"},
new String[]{"/templates/orion-server-module-entity-request-query.java.vm", "${type}QueryRequest.java", "entity.request.${bizPackage}"},
// convert 文件
new String[]{"/templates/orion-server-module-convert.java.vm", "%sConvert.java", "convert"},
// junit test 文件
new String[]{"/templates/orion-server-module-convert.java.vm", "${type}Convert.java", "convert"},
// -------------------- 后端 - provider --------------------
// api 文件
new String[]{"/templates/orion-server-provider-api.java.vm", "%sApi.java", "api"},
new String[]{"/templates/orion-server-provider-api.java.vm", "${type}Api.java", "api"},
// api impl 文件
new String[]{"/templates/orion-server-provider-api-impl.java.vm", "%sApiImpl.java", "api.impl"},
new String[]{"/templates/orion-server-provider-api-impl.java.vm", "${type}ApiImpl.java", "api.impl"},
// dto 文件
new String[]{"/templates/orion-server-provider-entity-dto.java.vm", "%sDTO.java", "entity.dto.%s"},
new String[]{"/templates/orion-server-provider-entity-dto.java.vm", "${type}DTO.java", "entity.dto.${bizPackage}"},
// create dto 文件
new String[]{"/templates/orion-server-provider-entity-dto-create.java.vm", "%sCreateDTO.java", "entity.dto.%s"},
new String[]{"/templates/orion-server-provider-entity-dto-create.java.vm", "${type}CreateDTO.java", "entity.dto.${bizPackage}"},
// update dto 文件
new String[]{"/templates/orion-server-provider-entity-dto-update.java.vm", "%sUpdateDTO.java", "entity.dto.%s"},
new String[]{"/templates/orion-server-provider-entity-dto-update.java.vm", "${type}UpdateDTO.java", "entity.dto.${bizPackage}"},
// query dto 文件
new String[]{"/templates/orion-server-provider-entity-dto-query.java.vm", "%sQueryDTO.java", "entity.dto.%s"},
new String[]{"/templates/orion-server-provider-entity-dto-query.java.vm", "${type}QueryDTO.java", "entity.dto.${bizPackage}"},
// convert 文件
new String[]{"/templates/orion-server-provider-convert.java.vm", "%sProviderConvert.java", "convert"},
new String[]{"/templates/orion-server-provider-convert.java.vm", "${type}ProviderConvert.java", "convert"},
// -------------------- 后端 - test --------------------
// unit test 文件
new String[]{"/templates/orion-server-test-service-tests.java.vm", "${type}ServiceTests.java", "service.impl"},
// create table sql 文件
new String[]{"/templates/orion-server-test-create-table.sql.vm", "create-table-h2-${tableName}.sql", "sql"},
// -------------------- 前端 --------------------
// vue api 文件
// api 文件
new String[]{"/templates/orion-vue-api.ts.vm", "${feature}.ts", "vue/api/${module}"},
// vue router 文件
// router 文件
new String[]{"/templates/orion-vue-router.ts.vm", "${module}.${feature}.ts", "vue/router/routes/modules"},
// vue views index.ts 文件
// views index.ts 文件
new String[]{"/templates/orion-vue-views-index.vue.vm", "index.vue", "vue/views/${module}/${feature}"},
// vue form-modal.vue 文件
// form-modal.vue 文件
new String[]{"/templates/orion-vue-views-components-form-modal.vue.vm", "${feature}-form-modal.vue", "vue/views/${module}/${feature}/components"},
// vue table.vue 文件
// table.vue 文件
new String[]{"/templates/orion-vue-views-components-table.vue.vm", "${feature}-table.vue", "vue/views/${module}/${feature}/components"},
// vue enum.types.ts 文件
// enum.types.ts 文件
new String[]{"/templates/orion-vue-views-types-enum.types.ts.vm", "enum.types.ts", "vue/views/${module}/${feature}/types"},
// vue form.rules.ts 文件
// form.rules.ts 文件
new String[]{"/templates/orion-vue-views-types-form.rules.ts.vm", "form.rules.ts", "vue/views/${module}/${feature}/types"},
// vue table.vue 文件
// table.vue 文件
new String[]{"/templates/orion-vue-views-types-table.columns.ts.vm", "table.columns.ts", "vue/views/${module}/${feature}/types"},
// sql menu.sql 文件
// menu.sql 文件
new String[]{"/templates/orion-sql-menu.sql.vm", "${feature}-menu.sql", "sql"},
};
@@ -353,12 +360,23 @@ public class CodeGenerator {
}).collect(Collectors.toList());
// 注入配置
InjectionConfig injection = new InjectionConfig.Builder()
return new InjectionConfig.Builder()
// 自定义 文件
.customFile(customerFiles)
// 构建
.build();
return injection;
}
/**
* 打印提示信息
*/
private static void printTips() {
String line = AnsiColor.GLOSS_GREEN.color(":: 代码生成完毕 ::\n") +
AnsiColor.GLOSS_BLUE.color("- 后端代码复制后请先 clean 模块父工程\n") +
AnsiColor.GLOSS_BLUE.color("- 后端代码复制后请先执行单元测试检测是否正常\n") +
AnsiColor.GLOSS_BLUE.color("- vue 代码需要注意同一模块的 router 需要自行合并\n") +
AnsiColor.SUFFIX;
System.out.print(line);
}
}

View File

@@ -38,6 +38,11 @@ public class GenTable {
*/
private boolean genProviderApi;
/**
* 是否生成单元测试
*/
private boolean genUnitTest;
// -------------------- 前端 --------------------
/**
@@ -61,24 +66,31 @@ public class GenTable {
private List<Class<? extends Enum<?>>> enums;
public GenTable(String tableName, String comment, String bizPackage) {
this(tableName, comment, bizPackage, false);
}
public GenTable(String tableName, String comment, String bizPackage, boolean genProviderApi) {
this.tableName = tableName;
this.comment = comment;
this.bizPackage = bizPackage;
this.genProviderApi = genProviderApi;
this.genProviderApi = true;
this.genUnitTest = true;
this.enums = new ArrayList<>();
}
/**
* 是否生成 api
* 忽略生成 api
*
* @return this
*/
public GenTable api() {
this.genProviderApi = true;
public GenTable ignoreApi() {
this.genProviderApi = false;
return this;
}
/**
* 忽略生成单元测试
*
* @return this
*/
public GenTable ignoreTest() {
this.genUnitTest = false;
return this;
}

View File

@@ -28,6 +28,7 @@ import com.orion.lang.utils.Strings;
import com.orion.lang.utils.io.Files1;
import com.orion.lang.utils.reflect.BeanMap;
import com.orion.lang.utils.reflect.Fields;
import com.orion.ops.framework.common.constant.Const;
import com.orion.ops.framework.common.constant.OrionOpsProConst;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
@@ -54,8 +55,6 @@ import java.util.stream.Collectors;
*/
public class VelocityTemplateEngine extends AbstractTemplateEngine {
private static final String[] PACKAGE_REPLACER = new String[]{"request.%s", "dto.%s"};
private final Map<String, GenTable> tables;
private VelocityEngine velocityEngine;
@@ -106,8 +105,27 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
return filePath.endsWith(dotVm) ? filePath : filePath + dotVm;
}
@Override
protected void outputCustomFile(@NotNull List<CustomFile> customFiles, @NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
// 创建自定义文件副本文件
customFiles = this.createCustomFilesBackup(customFiles, tableInfo);
// 添加表元数据
this.addTableMeta(tableInfo, objectMap);
// 替换自定义包名
this.replacePackageName(customFiles, tableInfo, objectMap);
// 添加注释元数据
this.addApiCommentMeta(tableInfo, objectMap);
// 生成后端文件
this.generatorServerFile(customFiles, tableInfo, objectMap);
// 生成前端文件
this.generatorVueFile(customFiles, tableInfo, objectMap);
}
/**
* 创建自定义文件副本对象
* <p>
* - 根据类型进行移除不需要生成的模板
*
* @param originCustomerFile originCustomerFile
* @param tableInfo tableInfo
@@ -131,6 +149,10 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
if (!table.isGenProviderApi()) {
files.removeIf(file -> this.isServerProviderFile(file.getTemplatePath()));
}
// 不生成单元测试文件
if (!table.isGenUnitTest()) {
files.removeIf(file -> this.isServerUnitTestFile(file.getTemplatePath()));
}
// 不生成 vue 文件
if (!table.isGenVue()) {
files.removeIf(file -> this.isVueFile(file.getTemplatePath()));
@@ -138,6 +160,28 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
return files;
}
/**
* 插入表元数据
*
* @param tableInfo tableInfo
* @param objectMap objectMap
*/
private void addTableMeta(@NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
// http 注释标识
objectMap.put("httpComment", "###");
// 版本
objectMap.put("since", OrionOpsProConst.VERSION);
// 替换业务注释
tableInfo.setComment(tables.get(tableInfo.getName()).getComment());
// 实体名称
String domainName = tableInfo.getEntityName();
String mappingHyphen = objectMap.get("controllerMappingHyphen").toString();
String entityName = domainName.substring(0, domainName.length() - 2);
objectMap.put("type", entityName);
objectMap.put("typeLower", Strings.firstLower(entityName));
objectMap.put("typeHyphen", mappingHyphen.substring(0, mappingHyphen.length() - 3));
}
/**
* 替换自定义文件包
*
@@ -152,10 +196,11 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
BiConsumer<String, Object> callSetter = (field, value) -> Fields.setFieldValue(s, field, value);
String packageName = s.getPackageName();
// 替换文件业务包名
boolean replace = Arrays.stream(PACKAGE_REPLACER).anyMatch(packageName::contains);
if (replace) {
String replacePackage = String.format(packageName, tables.get(tableInfo.getName()).getBizPackage());
callSetter.accept("packageName", replacePackage);
if (packageName.contains(Const.DOLLAR)) {
Map<String, Object> meta = new HashMap<>(4);
meta.put("bizPackage", tables.get(tableInfo.getName()).getBizPackage());
// 调用 setter
callSetter.accept("packageName", Strings.format(packageName, meta));
}
});
@@ -181,29 +226,6 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
objectMap.put("customProviderFilePackages", customProviderFilePackages);
}
/**
* 插入表元数据
*
* @param tableInfo tableInfo
* @param objectMap objectMap
*/
private void addTableMeta(@NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
// http 注释标识
objectMap.put("httpComment", "###");
// 版本
objectMap.put("since", OrionOpsProConst.VERSION);
// 替换业务注释
tableInfo.setComment(tables.get(tableInfo.getName()).getComment());
// 实体名称
String domainName = tableInfo.getEntityName();
String mappingHyphen = objectMap.get("controllerMappingHyphen").toString();
String entityName = domainName.substring(0, domainName.length() - 2);
objectMap.put("type", entityName);
objectMap.put("typeLower", Strings.firstLower(entityName));
objectMap.put("typeHyphen", mappingHyphen.substring(0, mappingHyphen.length() - 3));
}
/**
* 插入 api 注释
*
@@ -211,7 +233,7 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
* @param objectMap objectMap
*/
private void addApiCommentMeta(@NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
Map<String, String> map = new HashMap<>();
Map<String, String> map = new HashMap<>(12);
objectMap.put("apiComment", map);
String comment = tableInfo.getComment();
map.put("create", "创建" + comment);
@@ -225,31 +247,6 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
map.put("batchDeleteByIdList", "通过 id 批量删除" + comment);
}
@Override
protected void outputCustomFile(@NotNull List<CustomFile> customFiles, @NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
// 创建自定义文件副本文件
customFiles = this.createCustomFilesBackup(customFiles, tableInfo);
// 替换自定义包名
this.replacePackageName(customFiles, tableInfo, objectMap);
// 添加表元数据
this.addTableMeta(tableInfo, objectMap);
// 添加注释元数据
this.addApiCommentMeta(tableInfo, objectMap);
// 生成后端文件
List<CustomFile> serverFiles = customFiles.stream()
.filter(s -> this.isServerFile(s.getTemplatePath()))
.collect(Collectors.toList());
this.generatorServerFile(serverFiles, tableInfo, objectMap);
// 生成前端文件
if (tables.get(tableInfo.getName()).isGenVue()) {
List<CustomFile> vueFiles = customFiles.stream()
.filter(s -> this.isVueFile(s.getTemplatePath()))
.collect(Collectors.toList());
this.generatorVueFile(vueFiles, tableInfo, objectMap);
}
}
/**
* 生成后端文件
*
@@ -258,6 +255,11 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
* @param objectMap objectMap
*/
private void generatorServerFile(@NotNull List<CustomFile> customFiles, @NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
// 过滤文件
customFiles = customFiles.stream()
.filter(s -> this.isServerFile(s.getTemplatePath()))
.collect(Collectors.toList());
String parentPath = getPathInfo(OutputFile.parent);
// 生成文件
customFiles.forEach(file -> {
@@ -269,8 +271,13 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
// 文件路径
String filePath = parentPath + File.separator + file.getPackageName()
.replaceAll("\\.", StringPool.BACK_SLASH + File.separator);
String fileName = filePath + File.separator + String.format(file.getFileName(), objectMap.get("type"));
outputFile(Files1.newFile(fileName), objectMap, file.getTemplatePath(), file.isFileOverride());
// 文件名称
Map<String, Object> meta = new HashMap<>(4);
meta.put("type", objectMap.get("type"));
meta.put("tableName", tableInfo.getName());
String fileName = filePath + File.separator + Strings.format(file.getFileName(), meta);
// 渲染文件
this.outputFile(Files1.newFile(fileName), objectMap, file.getTemplatePath(), file.isFileOverride());
});
}
@@ -282,6 +289,16 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
* @param objectMap objectMap
*/
private void generatorVueFile(@NotNull List<CustomFile> customFiles, @NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
// 不生成 vue 文件
if (!tables.get(tableInfo.getName()).isGenVue()) {
return;
}
// 过滤文件
customFiles = customFiles.stream()
.filter(s -> this.isVueFile(s.getTemplatePath()))
.collect(Collectors.toList());
// 元数据
String outPath = getConfigBuilder().getGlobalConfig().getOutputDir();
GenTable table = tables.get(tableInfo.getName());
BeanMap beanMap = BeanMap.create(table, "enums");
@@ -301,7 +318,7 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
String filePath = outPath
+ "/" + Strings.format(file.getPackageName(), beanMap)
+ "/" + Strings.format(file.getFileName(), beanMap);
// 输出文件
// 渲染文件
this.outputFile(Files1.newFile(filePath), objectMap, file.getTemplatePath(), file.isFileOverride());
});
}
@@ -320,12 +337,22 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
* 是否为后端 provider 文件
*
* @param templatePath templatePath
* @return 是否为 sql 文件
* @return 是否为后端 provider 文件
*/
private boolean isServerProviderFile(String templatePath) {
return templatePath.contains("orion-server-provider");
}
/**
* 是否为后端单元测试文件
*
* @param templatePath templatePath
* @return 是否为后端单元测试文件
*/
private boolean isServerUnitTestFile(String templatePath) {
return templatePath.contains("orion-server-test");
}
/**
* 是否为 vue 文件
*

View File

@@ -40,9 +40,9 @@ Content-Type: application/json
Authorization: {{token}}
{
#foreach($field in ${table.fields})
#foreach($field in ${table.fields})
"${field.propertyName}": ""#if($foreach.hasNext),#end
#end
#end
}
@@ -52,9 +52,11 @@ Content-Type: application/json
Authorization: {{token}}
{
#foreach($field in ${table.fields})
"page": 1,
"limit": 10,
#foreach($field in ${table.fields})
"${field.propertyName}": ""#if($foreach.hasNext),#end
#end
#end
}

View File

@@ -1,6 +1,7 @@
package ${package.Controller};
import com.orion.lang.define.wrapper.DataGrid;
import com.orion.lang.define.wrapper.IPageRequest;
import com.orion.ops.framework.common.annotation.IgnoreLog;
import com.orion.ops.framework.common.annotation.RestWrapper;
import com.orion.ops.framework.common.constant.IgnoreLogMode;
@@ -89,7 +90,7 @@ public class ${table.controllerName} {
@PostMapping("/query")
@Operation(summary = "${apiComment.queryPage}")
@PreAuthorize("@ss.hasPermission('${package.ModuleName}:${typeHyphen}:query')")
public DataGrid<${type}VO> get${type}Page(@Validated @RequestBody ${type}QueryRequest request) {
public DataGrid<${type}VO> get${type}Page(@Validated(IPageRequest.class) @RequestBody ${type}QueryRequest request) {
return ${typeLower}Service.get${type}Page(request);
}

View File

@@ -17,7 +17,7 @@ import java.util.List;
*/
@Mapper
public interface ${type}Convert {
${type}Convert MAPPER = Mappers.getMapper(${type}Convert.class);
${type}DO to(${type}CreateRequest request);

View File

@@ -144,7 +144,7 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
boolean present = ${typeLower}DAO.of().wrapper(wrapper).present();
Valid.isFalse(present, ErrorMessage.DATA_PRESENT);
}
/**
* 构建查询 wrapper
*

View File

@@ -62,7 +62,7 @@ public interface ${table.serviceName} {
* @param request request
* @return count
*/
Long get${type}Count(Favorite${type}Request request);
Long get${type}Count(${type}QueryRequest request);
/**
* ${apiComment.queryPage}

View File

@@ -35,7 +35,7 @@ public class ${type}ApiImpl implements ${type}Api {
@Resource
private ${type}Service ${typeLower}Service;
@Resource
private ${type}DAO ${typeLower}DAO;
@@ -93,11 +93,11 @@ public class ${type}ApiImpl implements ${type}Api {
// 查询
return ${typeLower}DAO.of()
.wrapper(wrapper)
.dataGrid(${type}ProviderConvert.MAPPER::to);
.list(${type}ProviderConvert.MAPPER::to);
}
@Override
public Long get${type}Count(FavoriteQueryDTO dto) {
public Long get${type}Count(${type}QueryDTO dto) {
log.info("${type}Api.get${type}Count dto: {}", JSON.toJSONString(dto));
Valid.valid(dto);
// 条件

View File

@@ -0,0 +1,17 @@
-- $!{table.comment}
DROP TABLE IF EXISTS `${table.name}`;
CREATE TABLE `${table.name}`
(
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'id',
#foreach($field in ${table.fields})
#if("$!field.propertyName" != "id")
`${field.columnName}` ${field.metaInfo.jdbcType}(${field.metaInfo.length})#if(!$field.metaInfo.nullable) NOT NULL#end#if($null.isNull($field.metaInfo.defaultValue) || "$!{field.metaInfo.defaultValue}" == "") DEFAULT NULL#else DEFAULT#if(${field.propertyType} == 'String') '${field.metaInfo.defaultValue}'#else ${field.metaInfo.defaultValue}#end#end COMMENT '$!{field.metaInfo.remarks}',
#end
#end
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
`creator` VARCHAR(64) DEFAULT NULL COMMENT '创建人',
`updater` VARCHAR(64) DEFAULT NULL COMMENT '更新人',
`deleted` TINYINT DEFAULT '0' COMMENT '是否删除 0未删除 1已删除',
PRIMARY KEY (`id`)
);

View File

@@ -0,0 +1,105 @@
package ${currentPackage};
import com.orion.lang.define.wrapper.DataGrid;
import com.orion.lang.utils.collect.Lists;
import com.orion.ops.framework.test.core.base.BaseUnitTest;
import com.orion.ops.framework.test.core.utils.EntityRandoms;
#foreach($pkg in ${customModuleFilePackages})
import ${pkg}.*;
#end
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;
import javax.annotation.Resource;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* $!{table.comment} 服务单元测试
*
* @author Jiahang Li
* @version 1.0.0
* @since 2023/8/23 10:36
*/
@Slf4j
@Import(${type}ServiceImpl.class)
public class ${type}ServiceTests extends BaseUnitTest {
@Resource
private ${type}Service ${typeLower}Service;
private static Long lastId;
@Test
@Order(1)
public void create${type}Test() {
${type}CreateRequest req = EntityRandoms.random(${type}CreateRequest.class);
lastId = ${typeLower}Service.create${type}(req);
assertNotNull(lastId);
}
@Test
@Order(2)
public void update${type}ByIdTest() {
${type}UpdateRequest req = EntityRandoms.random(${type}UpdateRequest.class);
req.setId(lastId);
Integer effect = ${typeLower}Service.update${type}ById(req);
assertEquals(effect, 1);
}
@Test
@Order(3)
public void get${type}ByIdTest() {
${type}VO row = ${typeLower}Service.get${type}ById(lastId);
assertNotNull(row);
}
@Test
@Order(4)
public void get${type}ByIdListTest() {
List<${type}VO> rows = ${typeLower}Service.get${type}ByIdList(Lists.of(lastId));
assertFalse(rows.isEmpty());
}
@Test
@Order(5)
public void get${type}ListTest() {
List<${type}VO> rows = ${typeLower}Service.get${type}List(new ${type}QueryRequest());
assertFalse(rows.isEmpty());
}
@Test
@Order(6)
public void get${type}CountTest() {
Long count = ${typeLower}Service.get${type}Count(new ${type}QueryRequest());
assertEquals(count, 1L);
}
@Test
@Order(7)
public void get${type}PageTest() {
${type}QueryRequest request = new ${type}QueryRequest();
request.setPage(1);
request.setLimit(1);
DataGrid<${type}VO> dataGrid = ${typeLower}Service.get${type}Page(request);
assertFalse(dataGrid.isEmpty());
}
@Test
@Order(8)
public void delete${type}ByIdTest() {
Integer effect = ${typeLower}Service.delete${type}ById(lastId);
assertEquals(effect, 1);
}
@Test
@Order(9)
public void batchDelete${type}ByIdListTest() {
Integer effect = ${typeLower}Service.batchDelete${type}ByIdList(Lists.of(lastId));
assertEquals(effect, 0);
}
}

View File

@@ -16,7 +16,7 @@ spring:
sql:
init:
schema-locations:
- classpath:/sql/create-tables-h2-*.sql
- classpath:/sql/create-table-h2-*.sql
redis:
host: 127.0.0.1
port: 16379