轉載自:https://blog.csdn.net/qq_28177261/article/details/96432568
有的項目需要單元測試覆蓋率的行數達到一定的比例,通常情況下POJO類基本僅僅只是get、set方法,但又占據一大部分的代碼行數,通過以下方法可以節省一部分的勞動力。
- 首先POJO類get、set方法不能有復雜的邏輯操作(如果有最好過濾掉)
- 通過反射創建實例對象,同時獲取該類的Field[]
- 通過屬性描述符PropertyDescriptor獲取對應字段的Method
- 調用Method的invoke方法執行get、set方法
具體的執行流程
- 例如POJO類People:
public class People {
private String name;
private Integer age;
private String aLike;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getaLike() {
return aLike;
}
public void setaLike(String aLike) {
this.aLike = aLike;
}
}
- test包下創建父類BaseVoTest,子類只需繼承父類,實現父類的getT()方法,返回具體的實例
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public abstract class BaseVoTest<T> {
protected abstract T getT();
/**
* model的get和set方法
* 1.子類返回對應的類型
*2.通過反射創建類的實例
*3.獲取該類所有屬性字段,遍歷獲取每個字段對應的get、set方法,並執行
*/
private void testGetAndSet() throws IllegalAccessException, InstantiationException, IntrospectionException,
InvocationTargetException {
T t = getT();
Class modelClass = t.getClass();
Object obj = modelClass.newInstance();
Field[] fields = modelClass.getDeclaredFields();
for (Field f : fields) {
//JavaBean屬性名要求:前兩個字母要么都大寫,要么都小寫
//對於首字母是一個單詞的情況,要么過濾掉,要么自己拼方法名
//f.isSynthetic()過濾合成字段
if (f.getName().equals("aLike")
|| 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 {
this.testGetAndSet();
}
}
這樣People的單元測試覆蓋率就達到了70%(過濾了aLike字段,如果要達到100%,可以拼get、set方法名)