1. 手动合并存在重复被合并的文件,并统一包名
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
package com.zt.plat.framework.test.config;
|
||||
|
||||
import com.github.fppt.jedismock.RedisServer;
|
||||
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Redis 测试 Configuration,主要实现内嵌 Redis 的启动
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Lazy(false) // 禁止延迟加载
|
||||
@EnableConfigurationProperties(RedisProperties.class)
|
||||
public class RedisTestConfiguration {
|
||||
|
||||
/**
|
||||
* 创建模拟的 Redis Server 服务器
|
||||
*/
|
||||
@Bean
|
||||
public RedisServer redisServer(RedisProperties properties) throws IOException {
|
||||
RedisServer redisServer = new RedisServer(properties.getPort());
|
||||
// 一次执行多个单元测试时,貌似创建多个 spring 容器,导致不进行 stop。这样,就导致端口被占用,无法启动。。。
|
||||
try {
|
||||
redisServer.start();
|
||||
} catch (Exception ignore) {}
|
||||
return redisServer;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.zt.plat.framework.test.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
|
||||
import org.springframework.boot.autoconfigure.sql.init.SqlInitializationProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.init.DataSourceScriptDatabaseInitializer;
|
||||
import org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer;
|
||||
import org.springframework.boot.sql.init.DatabaseInitializationSettings;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* SQL 初始化的测试 Configuration
|
||||
*
|
||||
* 为什么不使用 org.springframework.boot.autoconfigure.sql.init.DataSourceInitializationConfiguration 呢?
|
||||
* 因为我们在单元测试会使用 spring.main.lazy-initialization 为 true,开启延迟加载。此时,会导致 DataSourceInitializationConfiguration 初始化
|
||||
* 不过呢,当前类的实现代码,基本是复制 DataSourceInitializationConfiguration 的哈!
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnMissingBean(AbstractScriptDatabaseInitializer.class)
|
||||
@ConditionalOnSingleCandidate(DataSource.class)
|
||||
@ConditionalOnClass(name = "org.springframework.jdbc.datasource.init.DatabasePopulator")
|
||||
@Lazy(value = false) // 禁止延迟加载
|
||||
@EnableConfigurationProperties(SqlInitializationProperties.class)
|
||||
public class SqlInitializationTestConfiguration {
|
||||
|
||||
@Bean
|
||||
public DataSourceScriptDatabaseInitializer dataSourceScriptDatabaseInitializer(DataSource dataSource,
|
||||
SqlInitializationProperties initializationProperties) {
|
||||
DatabaseInitializationSettings settings = createFrom(initializationProperties);
|
||||
return new DataSourceScriptDatabaseInitializer(dataSource, settings);
|
||||
}
|
||||
|
||||
static DatabaseInitializationSettings createFrom(SqlInitializationProperties properties) {
|
||||
DatabaseInitializationSettings settings = new DatabaseInitializationSettings();
|
||||
settings.setSchemaLocations(properties.getSchemaLocations());
|
||||
settings.setDataLocations(properties.getDataLocations());
|
||||
settings.setContinueOnError(properties.isContinueOnError());
|
||||
settings.setSeparator(properties.getSeparator());
|
||||
settings.setEncoding(properties.getEncoding());
|
||||
settings.setMode(properties.getMode());
|
||||
return settings;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceAutoConfigure;
|
||||
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
|
||||
import com.zt.plat.framework.common.biz.system.sequence.SequenceCommonApi;
|
||||
import com.zt.plat.framework.datasource.config.ZtDataSourceAutoConfiguration;
|
||||
import com.zt.plat.framework.mybatis.config.ZtMybatisAutoConfiguration;
|
||||
import com.zt.plat.framework.redis.config.ZtRedisAutoConfiguration;
|
||||
import com.zt.plat.framework.test.config.RedisTestConfiguration;
|
||||
import com.zt.plat.framework.test.config.SqlInitializationTestConfiguration;
|
||||
import org.redisson.spring.starter.RedissonAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.jdbc.Sql;
|
||||
|
||||
/**
|
||||
* 依赖内存 DB + Redis 的单元测试
|
||||
*
|
||||
* 相比 {@link BaseDbUnitTest} 来说,额外增加了内存 Redis
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = BaseDbAndRedisUnitTest.Application.class)
|
||||
@ActiveProfiles("unit-test") // 设置使用 application-unit-test 配置文件
|
||||
@Sql(scripts = "/sql/clean.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) // 每个单元测试结束后,清理 DB
|
||||
public class BaseDbAndRedisUnitTest {
|
||||
|
||||
@MockBean
|
||||
private SequenceCommonApi sequenceCommonApi;
|
||||
|
||||
@Import({
|
||||
// DB 配置类
|
||||
ZtDataSourceAutoConfiguration.class, // 自己的 DB 配置类
|
||||
DataSourceAutoConfiguration.class, // Spring DB 自动配置类
|
||||
DataSourceTransactionManagerAutoConfiguration.class, // Spring 事务自动配置类
|
||||
DruidDataSourceAutoConfigure.class, // Druid 自动配置类
|
||||
SqlInitializationTestConfiguration.class, // SQL 初始化
|
||||
// MyBatis 配置类
|
||||
ZtMybatisAutoConfiguration.class, // 自己的 MyBatis 配置类
|
||||
MybatisPlusAutoConfiguration.class, // MyBatis 的自动配置类
|
||||
|
||||
// Redis 配置类
|
||||
RedisTestConfiguration.class, // Redis 测试配置类,用于启动 RedisServer
|
||||
ZtRedisAutoConfiguration.class, // 自己的 Redis 配置类
|
||||
RedisAutoConfiguration.class, // Spring Redis 自动配置类
|
||||
RedissonAutoConfiguration.class, // Redisson 自动配置类
|
||||
|
||||
// 其它配置类
|
||||
SpringUtil.class
|
||||
})
|
||||
public static class Application {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceAutoConfigure;
|
||||
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
|
||||
import com.github.yulichang.autoconfigure.MybatisPlusJoinAutoConfiguration;
|
||||
import com.zt.plat.framework.common.biz.system.sequence.SequenceCommonApi;
|
||||
import com.zt.plat.framework.datasource.config.ZtDataSourceAutoConfiguration;
|
||||
import com.zt.plat.framework.mybatis.config.ZtMybatisAutoConfiguration;
|
||||
import com.zt.plat.framework.test.config.SqlInitializationTestConfiguration;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.cloud.openfeign.FeignClientFactory;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.jdbc.Sql;
|
||||
|
||||
/**
|
||||
* 依赖内存 DB 的单元测试
|
||||
*
|
||||
* 注意,Service 层同样适用。对于 Service 层的单元测试,我们针对自己模块的 Mapper 走的是 H2 内存数据库,针对别的模块的 Service 走的是 Mock 方法
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = BaseDbUnitTest.Application.class)
|
||||
@ActiveProfiles("unit-test") // 设置使用 application-unit-test 配置文件
|
||||
@Sql(scripts = "/sql/clean.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) // 每个单元测试结束后,清理 DB
|
||||
public class BaseDbUnitTest {
|
||||
|
||||
@MockBean
|
||||
private SequenceCommonApi sequenceCommonApi;
|
||||
|
||||
@MockBean
|
||||
private FeignClientFactory feignClientFactory;
|
||||
|
||||
@Import({
|
||||
// DB 配置类
|
||||
ZtDataSourceAutoConfiguration.class, // 自己的 DB 配置类
|
||||
DataSourceAutoConfiguration.class, // Spring DB 自动配置类
|
||||
DataSourceTransactionManagerAutoConfiguration.class, // Spring 事务自动配置类
|
||||
DruidDataSourceAutoConfigure.class, // Druid 自动配置类
|
||||
SqlInitializationTestConfiguration.class, // SQL 初始化
|
||||
// MyBatis 配置类
|
||||
ZtMybatisAutoConfiguration.class, // 自己的 MyBatis 配置类
|
||||
MybatisPlusAutoConfiguration.class, // MyBatis 的自动配置类
|
||||
MybatisPlusJoinAutoConfiguration.class, // MyBatis 的Join配置类
|
||||
|
||||
// 其它配置类
|
||||
SpringUtil.class
|
||||
})
|
||||
public static class Application {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
|
||||
import static com.zt.plat.framework.test.core.ut.GeneratorUtils.camelToKebabCase;
|
||||
import static com.zt.plat.framework.test.core.ut.GeneratorUtils.toPascalCase;
|
||||
|
||||
/**
|
||||
* 基础代码生成器,提供公共的生成逻辑
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
public abstract class BaseGenerator {
|
||||
|
||||
protected static final String BASE_PACKAGE = "com.zt.plat";
|
||||
protected static final TemplateEngine templateEngine = new TemplateEngine();
|
||||
|
||||
/**
|
||||
* 获取用户输入的基础信息
|
||||
*
|
||||
* @param prompt 提示信息
|
||||
* @return 包含用户输入信息的Map
|
||||
*/
|
||||
protected static Map<String, Object> getUserInput(String prompt) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
Map<String, Object> input = new HashMap<>();
|
||||
|
||||
System.out.print(prompt);
|
||||
input.put("names", scanner.nextLine());
|
||||
|
||||
System.out.print("请输入作者名称(例如:zt): ");
|
||||
input.put("author", scanner.nextLine());
|
||||
|
||||
System.out.print("请输入起始端口号(例如:8080): ");
|
||||
input.put("startPort", Integer.parseInt(scanner.nextLine()));
|
||||
|
||||
scanner.close();
|
||||
return input;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查目录是否已存在
|
||||
*
|
||||
* @param dir 目录路径
|
||||
* @param name 名称
|
||||
* @return 如果目录已存在返回true
|
||||
*/
|
||||
protected static boolean checkDirectoryExists(Path dir, String name) {
|
||||
if (Files.exists(dir)) {
|
||||
System.err.println("警告:'" + name + "' 已存在于 " + dir + ",跳过创建");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建基础模板变量
|
||||
*
|
||||
* @param name 名称
|
||||
* @param author 作者
|
||||
* @param port 端口
|
||||
* @return 模板变量Map
|
||||
*/
|
||||
protected Map<String, Object> createBaseVariables(String name, String author, int port) {
|
||||
String dashName = camelToKebabCase(name);
|
||||
String capitalizedName = toPascalCase(dashName);
|
||||
|
||||
Map<String, Object> variables = new HashMap<>();
|
||||
variables.put("originalName", name);
|
||||
variables.put("dashName", dashName);
|
||||
variables.put("packageName", dashName.replace("-", ""));
|
||||
variables.put("packagePathName", dashName.toLowerCase().replace('-', '/'));
|
||||
variables.put("capitalizedName", capitalizedName);
|
||||
variables.put("baseName", dashName.toLowerCase());
|
||||
variables.put("basePackage", BASE_PACKAGE);
|
||||
variables.put("author", author);
|
||||
variables.put("port", port);
|
||||
|
||||
return variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染配置文件模板
|
||||
*
|
||||
* @param resourcesDir 资源目录
|
||||
* @param templatePrefix 模板前缀
|
||||
* @param variables 模板变量
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
protected static void renderConfigFiles(Path resourcesDir, String templatePrefix, Map<String, Object> variables) throws IOException {
|
||||
templateEngine.renderToFile(templatePrefix + "/application.yml.vm",
|
||||
resourcesDir.resolve("application.yml"), variables);
|
||||
templateEngine.renderToFile(templatePrefix + "/application-dev.yml.vm",
|
||||
resourcesDir.resolve("application-dev.yml"), variables);
|
||||
templateEngine.renderToFile(templatePrefix + "/application-local.yml.vm",
|
||||
resourcesDir.resolve("application-local.yml"), variables);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取项目根路径
|
||||
*
|
||||
* @return 项目根路径
|
||||
*/
|
||||
protected static Path getProjectRoot() {
|
||||
return Paths.get("").toAbsolutePath();
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出完成信息
|
||||
*
|
||||
* @param names 名称数组
|
||||
* @param itemType 模块类型(如 "模块" 或 "服务器")
|
||||
* @param modulePattern XML模块模式
|
||||
*/
|
||||
protected static void printCompletionInfo(String[] names, String itemType, String modulePattern) {
|
||||
System.out.println("\n所有" + itemType + "创建完成!");
|
||||
System.out.println("请手动将以下" + itemType + "添加到根 pom.xml 的 <modules> 标签中:");
|
||||
|
||||
for (String name : names) {
|
||||
name = name.trim();
|
||||
if (!name.isEmpty()) {
|
||||
String dashName = camelToKebabCase(name);
|
||||
System.out.println("<module>" + modulePattern.replace("{name}", dashName) + "</module>");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量创建项目
|
||||
*
|
||||
* @param names 名称数组
|
||||
* @param author 作者
|
||||
* @param startPort 起始端口
|
||||
* @param itemType 项目类型描述
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
public void batchCreate(String[] names, String author, int startPort, String itemType) throws IOException {
|
||||
Path projectRoot = getProjectRoot();
|
||||
for (int i = 0; i < names.length; i++) {
|
||||
String name = names[i].trim();
|
||||
if (name.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int port = startPort + i;
|
||||
System.out.println("\n=== 开始创建" + itemType + ": " + name + " (端口: " + port + ") ===");
|
||||
createSingle(projectRoot, name, author, port);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建单个项目的抽象方法,由子类实现
|
||||
*
|
||||
* @param projectRoot 项目根路径
|
||||
* @param name 名称
|
||||
* @param author 作者
|
||||
* @param port 端口
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
protected abstract void createSingle(Path projectRoot, String name, String author, int port) throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
|
||||
import com.zt.plat.framework.common.biz.system.sequence.SequenceCommonApi;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
|
||||
/**
|
||||
* 纯 Mockito 的单元测试
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class BaseMockitoUnitTest {
|
||||
@MockBean
|
||||
private SequenceCommonApi sequenceCommonApi;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import com.zt.plat.framework.common.biz.system.sequence.SequenceCommonApi;
|
||||
import com.zt.plat.framework.redis.config.ZtRedisAutoConfiguration;
|
||||
import com.zt.plat.framework.test.config.RedisTestConfiguration;
|
||||
import org.redisson.spring.starter.RedissonAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.cloud.openfeign.FeignClientFactory;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
/**
|
||||
* 依赖内存 Redis 的单元测试
|
||||
*
|
||||
* 相比 {@link BaseDbUnitTest} 来说,从内存 DB 改成了内存 Redis
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = BaseRedisUnitTest.Application.class)
|
||||
@ActiveProfiles("unit-test") // 设置使用 application-unit-test 配置文件
|
||||
public class BaseRedisUnitTest {
|
||||
|
||||
@MockBean
|
||||
private SequenceCommonApi sequenceCommonApi;
|
||||
|
||||
@MockBean
|
||||
private FeignClientFactory feignClientFactory;
|
||||
|
||||
@Import({
|
||||
// Redis 配置类
|
||||
RedisTestConfiguration.class, // Redis 测试配置类,用于启动 RedisServer
|
||||
RedisAutoConfiguration.class, // Spring Redis 自动配置类
|
||||
ZtRedisAutoConfiguration.class, // 自己的 Redis 配置类
|
||||
RedissonAutoConfiguration.class, // Redisson 自动配置类
|
||||
|
||||
// 其它配置类
|
||||
SpringUtil.class
|
||||
})
|
||||
public static class Application {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 代码生成器通用工具类
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
public class GeneratorUtils {
|
||||
|
||||
/**
|
||||
* 首字母大写
|
||||
*
|
||||
* @param str 字符串
|
||||
* @return 首字母大写后的字符串
|
||||
*/
|
||||
public static String capitalize(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return str;
|
||||
}
|
||||
return str.substring(0, 1).toUpperCase() + str.substring(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将小驼峰命名转换为短横线分割的命名
|
||||
* 例如:orderManagement -> order-management
|
||||
*
|
||||
* @param camelCase 驼峰命名的字符串
|
||||
* @return 短横线分割的字符串
|
||||
*/
|
||||
public static String camelToKebabCase(String camelCase) {
|
||||
if (camelCase == null || camelCase.isEmpty()) {
|
||||
return camelCase;
|
||||
}
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < camelCase.length(); i++) {
|
||||
char c = camelCase.charAt(i);
|
||||
if (Character.isUpperCase(c) && i > 0) {
|
||||
result.append('-');
|
||||
}
|
||||
result.append(Character.toLowerCase(c));
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 kebab-case 转换为 PascalCase
|
||||
* 例如:demo-server -> DemoServer
|
||||
*
|
||||
* @param kebabCase 短横线分割的字符串
|
||||
* @return 帕斯卡命名的字符串
|
||||
*/
|
||||
public static String toPascalCase(String kebabCase) {
|
||||
if (kebabCase == null || kebabCase.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return Arrays.stream(kebabCase.split("-"))
|
||||
.map(s -> {
|
||||
if (s.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return s.substring(0, 1).toUpperCase() + s.substring(1);
|
||||
})
|
||||
.collect(Collectors.joining());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.zt.plat.framework.test.core.ut.GeneratorUtils.camelToKebabCase;
|
||||
|
||||
/**
|
||||
* Zt 模块代码生成器 - 使用 VM 模板
|
||||
*
|
||||
* 使用方法:
|
||||
* 1. 在 IDE 中,右键运行 {@link #main(String[])} 方法
|
||||
* 2. 根据提示,输入模块名,例如 "order"
|
||||
* 3. 根据提示,输入作者名,例如 "zt"
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
public class ModuleGenerator extends BaseGenerator {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
ModuleGenerator generator = new ModuleGenerator();
|
||||
|
||||
// 1. 获取用户输入
|
||||
Map<String, Object> input = getUserInput("请输入新模块的名称(支持多个模块,用逗号分割,例如:order,userManagement,payment): ");
|
||||
|
||||
String moduleNames = (String) input.get("names");
|
||||
String author = (String) input.get("author");
|
||||
int startPort = (Integer) input.get("startPort");
|
||||
|
||||
// 分割模块名
|
||||
String[] modules = moduleNames.split(",");
|
||||
|
||||
// 2. 批量创建模块
|
||||
generator.batchCreate(modules, author, startPort, "模块");
|
||||
|
||||
// 3. 输出完成信息
|
||||
printCompletionInfo(modules, "模块", "zt-module-{name}");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createSingle(Path projectRoot, String moduleName, String author, int port) throws IOException {
|
||||
// 将小驼峰转换为短横线分割的模块名
|
||||
String dashModuleName = camelToKebabCase(moduleName);
|
||||
|
||||
// 定义新模块路径
|
||||
Path newModuleDir = projectRoot.resolve("zt-module-" + dashModuleName);
|
||||
|
||||
if (checkDirectoryExists(newModuleDir, dashModuleName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("将在以下位置创建新模块: " + newModuleDir);
|
||||
|
||||
// 准备模板变量
|
||||
Map<String, Object> variables = createBaseVariables(moduleName, author, port);
|
||||
variables.put("moduleName", moduleName);
|
||||
variables.put("dashModuleName", dashModuleName);
|
||||
variables.put("capitalizedModuleName", variables.get("capitalizedName"));
|
||||
variables.put("moduleDescription", variables.get("capitalizedName") + " 模块");
|
||||
variables.put("applicationClassName", variables.get("capitalizedName") + "ServerApplication");
|
||||
|
||||
// 创建模块结构
|
||||
createModuleStructure(newModuleDir, variables);
|
||||
|
||||
System.out.println("模块 '" + dashModuleName + "' 创建成功!");
|
||||
}
|
||||
|
||||
private void createModuleStructure(Path moduleDir, Map<String, Object> variables) throws IOException {
|
||||
String dashModuleName = (String) variables.get("dashModuleName");
|
||||
String packageName = (String) variables.get("packageName");
|
||||
String basePackage = (String) variables.get("basePackage");
|
||||
String capitalizedModuleName = (String) variables.get("capitalizedName");
|
||||
String applicationClassName = (String) variables.get("applicationClassName");
|
||||
String baseName = (String) variables.get("baseName");
|
||||
|
||||
// 创建主模块目录
|
||||
Files.createDirectories(moduleDir);
|
||||
|
||||
// 1. 创建主模块 pom.xml
|
||||
templateEngine.renderToFile("generator/module/pom.xml.vm",
|
||||
moduleDir.resolve("pom.xml"), variables);
|
||||
|
||||
// 2. 创建 API 模块
|
||||
Path apiDir = moduleDir.resolve("zt-module-" + dashModuleName + "-api");
|
||||
Files.createDirectories(apiDir);
|
||||
|
||||
// API 模块的 Java 源码目录
|
||||
Path apiJavaDir = apiDir.resolve("src/main/java")
|
||||
.resolve(basePackage.replace(".", "/"))
|
||||
.resolve("module")
|
||||
.resolve(packageName);
|
||||
Files.createDirectories(apiJavaDir);
|
||||
|
||||
// API 模块的错误码目录
|
||||
Path enumsDir = apiJavaDir.resolve("enums");
|
||||
Files.createDirectories(enumsDir);
|
||||
|
||||
templateEngine.renderToFile("generator/module/api-pom.xml.vm",
|
||||
apiDir.resolve("pom.xml"), variables);
|
||||
templateEngine.renderToFile("generator/module/ErrorCodeConstants.java.vm",
|
||||
enumsDir.resolve("ErrorCodeConstants.java"), variables);
|
||||
|
||||
// 3. 创建 Server 模块
|
||||
Path serverDir = moduleDir.resolve("zt-module-" + dashModuleName + "-server");
|
||||
Files.createDirectories(serverDir);
|
||||
|
||||
// Server 模块的 Java 源码目录
|
||||
Path serverJavaDir = serverDir.resolve("src/main/java")
|
||||
.resolve(basePackage.replace(".", "/"))
|
||||
.resolve("module")
|
||||
.resolve(packageName);
|
||||
Files.createDirectories(serverJavaDir);
|
||||
|
||||
// Controller 目录
|
||||
Path controllerDir = serverJavaDir.resolve("controller/admin").resolve(packageName);
|
||||
Files.createDirectories(controllerDir);
|
||||
|
||||
// Security 配置目录
|
||||
Path securityConfigDir = serverJavaDir.resolve("framework/security/config");
|
||||
Files.createDirectories(securityConfigDir);
|
||||
|
||||
// 资源目录
|
||||
Path resourcesDir = serverDir.resolve("src/main/resources");
|
||||
Files.createDirectories(resourcesDir);
|
||||
|
||||
templateEngine.renderToFile("generator/module/server-pom.xml.vm",
|
||||
serverDir.resolve("pom.xml"), variables);
|
||||
templateEngine.renderToFile("generator/module/ServerApplication.java.vm",
|
||||
serverJavaDir.resolve(applicationClassName + ".java"), variables);
|
||||
templateEngine.renderToFile("generator/module/Controller.java.vm",
|
||||
controllerDir.resolve(capitalizedModuleName + "Controller.java"), variables);
|
||||
templateEngine.renderToFile("generator/module/SecurityConfiguration.java.vm",
|
||||
securityConfigDir.resolve("SecurityConfiguration.java"), variables);
|
||||
templateEngine.renderToFile("generator/module/application.yml.vm",
|
||||
resourcesDir.resolve("application.yml"), variables);
|
||||
templateEngine.renderToFile("generator/module/application-dev.yml.vm",
|
||||
resourcesDir.resolve("application-dev.yml"), variables);
|
||||
templateEngine.renderToFile("generator/module/application-local.yml.vm",
|
||||
resourcesDir.resolve("application-local.yml"), variables);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.zt.plat.framework.test.core.ut.GeneratorUtils.toPascalCase;
|
||||
|
||||
/**
|
||||
* Zt Server 代码生成器 - 使用 VM 模板
|
||||
*
|
||||
* 使用方法:
|
||||
* 1. 在 IDE 中,右键运行 {@link #main(String[])} 方法
|
||||
* 2. 根据提示,输入新 Server 的名称,例如 "demo-server"
|
||||
* 3. 根据提示,输入作者名,例如 "zt"
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
public class ServerGenerator extends BaseGenerator {
|
||||
|
||||
private static final String BASE_PACKAGE_PREFIX = "com.zt.plat.";
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
ServerGenerator generator = new ServerGenerator();
|
||||
|
||||
// 1. 获取用户输入
|
||||
Map<String, Object> input = getUserInput("请输入新 Server 的基础名称(支持多个服务器,用逗号分割,例如:demo,admin,api): ");
|
||||
|
||||
String baseNames = (String) input.get("names");
|
||||
String author = (String) input.get("author");
|
||||
int startPort = (Integer) input.get("startPort");
|
||||
|
||||
// 分割服务名
|
||||
String[] servers = baseNames.split(",");
|
||||
|
||||
// 2. 批量创建服务器
|
||||
generator.batchCreate(servers, author, startPort, "服务器");
|
||||
|
||||
// 3. 输出完成信息
|
||||
printCompletionInfo(servers, "服务器", "{name}-server");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createSingle(Path projectRoot, String baseName, String author, int port) throws IOException {
|
||||
String serverName = baseName + "-server";
|
||||
|
||||
// 定义新 Server 路径
|
||||
Path newServerDir = projectRoot.resolve(serverName);
|
||||
|
||||
if (checkDirectoryExists(newServerDir, serverName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("将在以下位置创建新 Server: " + newServerDir);
|
||||
|
||||
// 准备模板变量
|
||||
Map<String, Object> variables = createBaseVariables(baseName, author, port);
|
||||
variables.put("serverName", serverName);
|
||||
variables.put("capitalizedBaseName", variables.get("capitalizedName"));
|
||||
variables.put("serverDescription", variables.get("capitalizedName") + " 服务器");
|
||||
variables.put("applicationClassName", toPascalCase(serverName) + "Application");
|
||||
|
||||
// 创建目录结构和文件
|
||||
createServerStructure(newServerDir, variables);
|
||||
|
||||
System.out.println("Server '" + serverName + "' 创建成功!");
|
||||
}
|
||||
|
||||
private void createServerStructure(Path serverDir, Map<String, Object> variables) throws IOException {
|
||||
String packageName = (String) variables.get("packageName");
|
||||
String basePackage = (String) variables.get("basePackage");
|
||||
String baseName = (String) variables.get("baseName");
|
||||
String applicationClassName = (String) variables.get("applicationClassName");
|
||||
|
||||
// 创建基础目录结构
|
||||
Files.createDirectories(serverDir);
|
||||
|
||||
// 创建 Java 源码目录结构
|
||||
Path javaSourceDir = serverDir.resolve("src/main/java")
|
||||
.resolve(basePackage.replace(".", "/"))
|
||||
.resolve(packageName);
|
||||
Files.createDirectories(javaSourceDir);
|
||||
|
||||
// 创建控制器目录
|
||||
Path controllerDir = javaSourceDir.resolve("controller").resolve(packageName);
|
||||
Files.createDirectories(controllerDir);
|
||||
|
||||
// 创建资源目录
|
||||
Path resourcesDir = serverDir.resolve("src/main/resources");
|
||||
Files.createDirectories(resourcesDir);
|
||||
|
||||
// 生成文件
|
||||
// 1. pom.xml
|
||||
templateEngine.renderToFile("generator/server/pom.xml.vm",
|
||||
serverDir.resolve("pom.xml"), variables);
|
||||
|
||||
// 2. 启动类
|
||||
templateEngine.renderToFile("generator/server/Application.java.vm",
|
||||
javaSourceDir.resolve(applicationClassName + ".java"), variables);
|
||||
|
||||
// 3. 示例控制器
|
||||
String controllerClassName = variables.get("capitalizedBaseName") + "Controller";
|
||||
templateEngine.renderToFile("generator/server/Controller.java.vm",
|
||||
controllerDir.resolve(controllerClassName + ".java"), variables);
|
||||
|
||||
// 4. 配置文件
|
||||
renderConfigFiles(resourcesDir, "generator/server", variables);
|
||||
|
||||
// 5. Dockerfile
|
||||
templateEngine.renderToFile("generator/server/Dockerfile.vm",
|
||||
serverDir.resolve("Dockerfile"), variables);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
|
||||
import cn.hutool.extra.template.TemplateConfig;
|
||||
import cn.hutool.extra.template.engine.velocity.VelocityEngine;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 模板引擎工具类,用于代码生成
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
public class TemplateEngine {
|
||||
|
||||
private final cn.hutool.extra.template.TemplateEngine velocityEngine;
|
||||
|
||||
public TemplateEngine() {
|
||||
TemplateConfig config = new TemplateConfig();
|
||||
config.setResourceMode(TemplateConfig.ResourceMode.CLASSPATH);
|
||||
this.velocityEngine = new VelocityEngine(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染模板
|
||||
*
|
||||
* @param templatePath 模板路径(相对于 resources 目录)
|
||||
* @param variables 变量映射
|
||||
* @return 渲染后的内容
|
||||
*/
|
||||
public String render(String templatePath, Map<String, Object> variables) {
|
||||
return velocityEngine.getTemplate(templatePath).render(variables);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染模板并写入文件
|
||||
*
|
||||
* @param templatePath 模板路径(相对于 resources 目录)
|
||||
* @param outputPath 输出文件路径
|
||||
* @param variables 变量映射
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
public void renderToFile(String templatePath, Path outputPath, Map<String, Object> variables) throws IOException {
|
||||
String content = render(templatePath, variables);
|
||||
Files.createDirectories(outputPath.getParent());
|
||||
Files.write(outputPath, content.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查模板文件是否存在
|
||||
*
|
||||
* @param templatePath 模板路径
|
||||
* @return 是否存在
|
||||
*/
|
||||
public boolean templateExists(String templatePath) {
|
||||
try {
|
||||
velocityEngine.getTemplate(templatePath);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* 提供单元测试 Unit Test 的基类
|
||||
*/
|
||||
package com.zt.plat.framework.test.core.ut;
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.zt.plat.framework.test.core.util;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.ReflectUtil;
|
||||
import com.zt.plat.framework.common.exception.ErrorCode;
|
||||
import com.zt.plat.framework.common.exception.ServiceException;
|
||||
import com.zt.plat.framework.common.exception.util.ServiceExceptionUtil;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* 单元测试,assert 断言工具类
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
public class AssertUtils {
|
||||
|
||||
/**
|
||||
* 比对两个对象的属性是否一致
|
||||
*
|
||||
* 注意,如果 expected 存在的属性,actual 不存在的时候,会进行忽略
|
||||
*
|
||||
* @param expected 期望对象
|
||||
* @param actual 实际对象
|
||||
* @param ignoreFields 忽略的属性数组
|
||||
*/
|
||||
public static void assertPojoEquals(Object expected, Object actual, String... ignoreFields) {
|
||||
Field[] expectedFields = ReflectUtil.getFields(expected.getClass());
|
||||
Arrays.stream(expectedFields).forEach(expectedField -> {
|
||||
// 忽略 jacoco 自动生成的 $jacocoData 属性的情况
|
||||
if (expectedField.isSynthetic()) {
|
||||
return;
|
||||
}
|
||||
// 如果是忽略的属性,则不进行比对
|
||||
if (ArrayUtil.contains(ignoreFields, expectedField.getName())) {
|
||||
return;
|
||||
}
|
||||
// 忽略不存在的属性
|
||||
Field actualField = ReflectUtil.getField(actual.getClass(), expectedField.getName());
|
||||
if (actualField == null) {
|
||||
return;
|
||||
}
|
||||
// 比对
|
||||
Assertions.assertEquals(
|
||||
ReflectUtil.getFieldValue(expected, expectedField),
|
||||
ReflectUtil.getFieldValue(actual, actualField),
|
||||
String.format("Field(%s) 不匹配", expectedField.getName())
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 比对两个对象的属性是否一致
|
||||
*
|
||||
* 注意,如果 expected 存在的属性,actual 不存在的时候,会进行忽略
|
||||
*
|
||||
* @param expected 期望对象
|
||||
* @param actual 实际对象
|
||||
* @param ignoreFields 忽略的属性数组
|
||||
* @return 是否一致
|
||||
*/
|
||||
public static boolean isPojoEquals(Object expected, Object actual, String... ignoreFields) {
|
||||
Field[] expectedFields = ReflectUtil.getFields(expected.getClass());
|
||||
return Arrays.stream(expectedFields).allMatch(expectedField -> {
|
||||
// 如果是忽略的属性,则不进行比对
|
||||
if (ArrayUtil.contains(ignoreFields, expectedField.getName())) {
|
||||
return true;
|
||||
}
|
||||
// 忽略不存在的属性
|
||||
Field actualField = ReflectUtil.getField(actual.getClass(), expectedField.getName());
|
||||
if (actualField == null) {
|
||||
return true;
|
||||
}
|
||||
return Objects.equals(ReflectUtil.getFieldValue(expected, expectedField),
|
||||
ReflectUtil.getFieldValue(actual, actualField));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行方法,校验抛出的 Service 是否符合条件
|
||||
*
|
||||
* @param executable 业务异常
|
||||
* @param errorCode 错误码对象
|
||||
* @param messageParams 消息参数
|
||||
*/
|
||||
public static void assertServiceException(Executable executable, ErrorCode errorCode, Object... messageParams) {
|
||||
// 调用方法
|
||||
ServiceException serviceException = assertThrows(ServiceException.class, executable);
|
||||
// 校验错误码
|
||||
Assertions.assertEquals(errorCode.getCode(), serviceException.getCode(), "错误码不匹配");
|
||||
String message = ServiceExceptionUtil.doFormat(errorCode.getCode(), errorCode.getMsg(), messageParams);
|
||||
Assertions.assertEquals(message, serviceException.getMessage(), "错误提示不匹配");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.zt.plat.framework.test.core.util;
|
||||
|
||||
import cn.hutool.core.date.LocalDateTimeUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.zt.plat.framework.common.enums.CommonStatusEnum;
|
||||
import uk.co.jemos.podam.api.PodamFactory;
|
||||
import uk.co.jemos.podam.api.PodamFactoryImpl;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* 随机工具类
|
||||
*
|
||||
* @author ZT
|
||||
*/
|
||||
public class RandomUtils {
|
||||
|
||||
private static final int RANDOM_STRING_LENGTH = 10;
|
||||
|
||||
private static final int TINYINT_MAX = 127;
|
||||
|
||||
private static final int RANDOM_DATE_MAX = 30;
|
||||
|
||||
private static final int RANDOM_COLLECTION_LENGTH = 5;
|
||||
|
||||
private static final PodamFactory PODAM_FACTORY = new PodamFactoryImpl();
|
||||
|
||||
static {
|
||||
// 字符串
|
||||
PODAM_FACTORY.getStrategy().addOrReplaceTypeManufacturer(String.class,
|
||||
(dataProviderStrategy, attributeMetadata, map) -> randomString());
|
||||
// Integer
|
||||
PODAM_FACTORY.getStrategy().addOrReplaceTypeManufacturer(Integer.class, (dataProviderStrategy, attributeMetadata, map) -> {
|
||||
// 如果是 status 的字段,返回 0 或 1
|
||||
if ("status".equals(attributeMetadata.getAttributeName())) {
|
||||
return RandomUtil.randomEle(CommonStatusEnum.values()).getStatus();
|
||||
}
|
||||
// 如果是 type、status 结尾的字段,返回 tinyint 范围
|
||||
if (StrUtil.endWithAnyIgnoreCase(attributeMetadata.getAttributeName(),
|
||||
"type", "status", "category", "scope", "result")) {
|
||||
return RandomUtil.randomInt(0, TINYINT_MAX + 1);
|
||||
}
|
||||
return RandomUtil.randomInt();
|
||||
});
|
||||
// LocalDateTime
|
||||
PODAM_FACTORY.getStrategy().addOrReplaceTypeManufacturer(LocalDateTime.class,
|
||||
(dataProviderStrategy, attributeMetadata, map) -> randomLocalDateTime());
|
||||
// Boolean
|
||||
PODAM_FACTORY.getStrategy().addOrReplaceTypeManufacturer(Boolean.class, (dataProviderStrategy, attributeMetadata, map) -> {
|
||||
// 如果是 deleted 的字段,返回非删除
|
||||
if ("deleted".equals(attributeMetadata.getAttributeName())) {
|
||||
return false;
|
||||
}
|
||||
return RandomUtil.randomBoolean();
|
||||
});
|
||||
}
|
||||
|
||||
public static String randomString() {
|
||||
return RandomUtil.randomString(RANDOM_STRING_LENGTH);
|
||||
}
|
||||
|
||||
public static Long randomLongId() {
|
||||
return RandomUtil.randomLong(0, Long.MAX_VALUE);
|
||||
}
|
||||
|
||||
public static Integer randomInteger() {
|
||||
return RandomUtil.randomInt(0, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
public static Date randomDate() {
|
||||
return RandomUtil.randomDay(0, RANDOM_DATE_MAX);
|
||||
}
|
||||
|
||||
public static LocalDateTime randomLocalDateTime() {
|
||||
// 设置 Nano 为零的原因,避免 MySQL、H2 存储不到时间戳
|
||||
return LocalDateTimeUtil.of(randomDate()).withNano(0);
|
||||
}
|
||||
|
||||
public static Short randomShort() {
|
||||
return (short) RandomUtil.randomInt(0, Short.MAX_VALUE);
|
||||
}
|
||||
|
||||
public static <T> Set<T> randomSet(Class<T> clazz) {
|
||||
return Stream.iterate(0, i -> i).limit(RandomUtil.randomInt(1, RANDOM_COLLECTION_LENGTH))
|
||||
.map(i -> randomPojo(clazz)).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public static Integer randomCommonStatus() {
|
||||
return RandomUtil.randomEle(CommonStatusEnum.values()).getStatus();
|
||||
}
|
||||
|
||||
public static String randomEmail() {
|
||||
return randomString() + "@qq.com";
|
||||
}
|
||||
|
||||
public static String randomMobile() {
|
||||
return "13800138" + RandomUtil.randomNumbers(3);
|
||||
}
|
||||
|
||||
public static String randomURL() {
|
||||
return "https://www.iocoder.cn/" + randomString();
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public static <T> T randomPojo(Class<T> clazz, Consumer<T>... consumers) {
|
||||
T pojo = PODAM_FACTORY.manufacturePojo(clazz);
|
||||
// 非空时,回调逻辑。通过它,可以实现 Pojo 的进一步处理
|
||||
if (ArrayUtil.isNotEmpty(consumers)) {
|
||||
Arrays.stream(consumers).forEach(consumer -> consumer.accept(pojo));
|
||||
}
|
||||
return pojo;
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public static <T> T randomPojo(Class<T> clazz, Type type, Consumer<T>... consumers) {
|
||||
T pojo = PODAM_FACTORY.manufacturePojo(clazz, type);
|
||||
// 非空时,回调逻辑。通过它,可以实现 Pojo 的进一步处理
|
||||
if (ArrayUtil.isNotEmpty(consumers)) {
|
||||
Arrays.stream(consumers).forEach(consumer -> consumer.accept(pojo));
|
||||
}
|
||||
return pojo;
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public static <T> List<T> randomPojoList(Class<T> clazz, Consumer<T>... consumers) {
|
||||
int size = RandomUtil.randomInt(1, RANDOM_COLLECTION_LENGTH);
|
||||
return randomPojoList(clazz, size, consumers);
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public static <T> List<T> randomPojoList(Class<T> clazz, int size, Consumer<T>... consumers) {
|
||||
return Stream.iterate(0, i -> i).limit(size).map(o -> randomPojo(clazz, consumers))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* 测试组件,用于单元测试、集成测试等等
|
||||
*/
|
||||
package com.zt.plat.framework.test;
|
||||
Reference in New Issue
Block a user