1、引入依赖
引入jmockdata
<dependency>
<groupId>com.github.jsonzou</groupId>
<artifactId>jmockdata</artifactId>
<version>4.1.2</version>
<scope>test</scope>
</dependency>
2、引入工具类
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.github.jsonzou.jmockdata.DataConfig;
import com.github.jsonzou.jmockdata.JMockData;
import com.github.jsonzou.jmockdata.MockConfig;
import com.github.jsonzou.jmockdata.Mocker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.Assert;
import org.springframework.util.SystemPropertyUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class BeanTestUtils {
private static final FixedStringMocker STRING_MOCKER = new FixedStringMocker();
private static final MockConfig mockConfig = MockConfig.newInstance();
private static final List<String> initialExcludeFieldNames = new ArrayList<>();
private static final ObjectMapper objectMapper = new ObjectMapper();
private static ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
private static MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
static {
initialExcludeFieldNames.add("$jacocoData");
initialExcludeFieldNames.add("serialVersionUID");
mockConfig.registerMocker(STRING_MOCKER, String.class);
mockConfig.sizeRange(0, 1);
}
public static void testPackages(List<String> packages, List<String> excludeFieldNames) {
List<Class<?>> classes = scanClasses(packages);
classes.stream().parallel().forEach(clazz -> {
try {
doGetSetTest(mockBean(clazz, excludeFieldNames));
} catch (Exception e) {
log.info(clazz.getName() + "getSet Test Error", e);
}
});
}
private static final MockConfig getMockConfig(List<String> excludeFieldNames) {
excludeFieldNames.addAll(initialExcludeFieldNames);
mockConfig.excludes(excludeFieldNames.toArray(new String[excludeFieldNames.size()]));
return mockConfig;
}
private static <T> T mockBean(Class<T> beanClazz, List<String> excludeFieldNames) {
Assert.notNull(beanClazz, "beanClazz can not be null");
MockConfig mockConfig = getMockConfig(excludeFieldNames);
T bean = null;
try {
bean = JMockData.mock(beanClazz, mockConfig);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
return bean;
}
private static class FixedStringMocker implements Mocker<String> {
@Override
public String mock(DataConfig mockConfig) {
return "mock data string";
}
}
private static ObjectMapper getObjectMapper() {
return objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
private static void doGetSetTest(Object o) {
String jsonStr = null;
try {
jsonStr = getObjectMapper().writeValueAsString(o);
} catch (JsonProcessingException e) {
e.printStackTrace();
org.junit.Assert.assertNotNull(jsonStr);
}
org.junit.Assert.assertNotNull(jsonStr);
}
private static List<Class<?>> scanClasses(List<String> packages) {
List<Class<?>> modelClazzList = new ArrayList<>();
packages.stream().forEach(modelPackage -> {
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ org.springframework.util.ClassUtils.convertClassNameToResourcePath(
SystemPropertyUtils.resolvePlaceholders(modelPackage)) + "/*.class";
Resource[] resources = null;
try {
resources = resourcePatternResolver.getResources(packageSearchPath);
} catch (IOException e) {
log.error("Can not get reources from [{}]", packageSearchPath, e);
}
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader = null;
try {
metadataReader = metadataReaderFactory.getMetadataReader(resource);
} catch (IOException e1) {
log.error("Can not found metaReader", e1);
continue;
}
Class<?> modelClazz = null;
try {
modelClazz = Class.forName(metadataReader.getClassMetadata().getClassName());
if (!modelClazz.isInterface()) {
modelClazzList.add(modelClazz);
}
} catch (ClassNotFoundException e) {
log.warn("Class [{}] not found just ignore.", modelClazz);
}
}
}
});
return modelClazzList;
}
}
3、测试类调用
支持使用表达式com.test.dto.**
@Slf4j
public class TestAllDto {
@Test
public void dtoTest() {
List<String> packages = Lists.newArrayList("com.test.dto","com.test.dto.req","com.test.dto.resp");
List<String> excludeFieldNames = Lists.newArrayList("aaa", "bbb", "ccc");
BeanTestUtils.testPackages(packages, excludeFieldNames);
Assert.assertNotNull(new DtoTestUtils());
}
}