针对POJO类get、set方法的单元测试覆盖

本文介绍了一种自动化进行POJO类单元测试的方法,通过反射和属性描述符PropertyDescriptor获取并执行get、set方法,显著提高测试覆盖率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有的项目需要单元测试覆盖率的行数达到一定的比例,通常情况下POJO类基本仅仅只是get、set方法,但又占据一大部分的代码行数,通过以下方法可以节省一部分的劳动力。

  1. 首先POJO类get、set方法不能有复杂的逻辑操作(如果有最好过滤掉)
  2. 通过反射创建实例对象,同时获取该类的Field[]
  3. 通过属性描述符PropertyDescriptor获取对应字段的Method
  4. 调用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方法名)

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值