有的项目需要单元测试覆盖率的行数达到一定的比例,通常情况下POJO类基本仅仅只是get、set方法,但又占据一大部分的代码行数,通过以下方法可以节省一部分的劳动力。
首先POJO类get、set方法不能有复杂的逻辑操作(如果有最好过滤掉);
通过反射创建实例对象,同时获取该类的Field[];
通过属性描述符PropertyDescriptor获取对应字段的Method;
调用Method的invoke方法执行get、set;
看具体的执行流程:
(1)test包下创建父类BaseVoTest,子类只需继承父类,实现父类的getT()方法,返回具体的Class;
@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(); } } |
(2)创建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; } } |
(3)test包下创建PeopleTest,继承BaseTest,实现getT()方法;
public class PeopleTest extends BaseVoTest<People> { @Override protected People getT() { return new People(); } } |
这样People的单元测试覆盖率就达到了70%(过滤了aLike字段,如果要达到100%,可以拼get、set方法名)。
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理