/**
* @Author zhaozhen
* @Date 2021/7/22 6:14 下午
* @Version 1.0 用来测试实体类,提高单测覆盖率。
*/@SpringBootTest@RunWith(MockitoJUnitRunner.class)publicabstractclassBaseVoEntityTest<T>{protectedabstract T getT();privatevoidtestGetAndSet()throws IllegalAccessException, InstantiationException, IntrospectionException,
InvocationTargetException, NoSuchMethodException {
T t =getT();
Class modelClass= t.getClass();
Object obj = modelClass.getDeclaredConstructor().newInstance();
Field[] fields = modelClass.getDeclaredFields();for(Field f : fields){boolean isStatic = Modifier.isStatic(f.getModifiers());// 过滤字段if(f.getName().equals("isSerialVersionUID")|| f.getName().equals("serialVersionUID")|| isStatic || f.getGenericType().toString().equals("boolean")|| f.isSynthetic()){continue;}
PropertyDescriptor pd =newPropertyDescriptor(f.getName(), modelClass);
Method get = pd.getReadMethod();
Method set = pd.getWriteMethod();
set.invoke(obj, get.invoke(obj));}}@TestpublicvoidgetAndSetTest()throws InvocationTargetException, IntrospectionException,
InstantiationException, IllegalAccessException, NoSuchMethodException {this.testGetAndSet();}}
使用示例
public class StudentTest extends BaseVoEntityTest<Student> {
private Student studentUnderTest;
@Before
public void setUp() {
studentUnderTest = new Student();
studentUnderTest.setId(1);
studentUnderTest.setAge(11);
studentUnderTest.setName("test");
}
@Test
public void testEquals() {
// Run the test
final boolean result = studentUnderTest.getName().equals("test");
// Verify the results
assertThat(result).isTrue();
}
@Override
protected Student getT() {
return studentUnderTest;
}
}