抽象类
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public abstract class BaseVoEntityTest<T> {
protected abstract T getT();
private void testGetAndSet() 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 = new PropertyDescriptor(f.getName(), modelClass);
Method get = pd.getReadMethod();
Method set = pd.getWriteMethod();
set.invoke(obj, get.invoke(obj));
}
}
@Test
public void getAndSetTest() 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;
}
}
|