4

用pl.pojo.tester测试Pojo类,提高测试覆盖率

 3 years ago
source link: https://www.pkslow.com/archives/pl-pojo-tester
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
技术之前,先读诗书:

桃奇满村春似锦,踏歌椎鼓过清明。

Java项目开发中,我们经常需要定义一些简单的类Pojo,如VODTO等,通常它们作为数据载体,只具有gettersettertoString等简单方法。而在单元测试中,因为有测试覆盖率的要求,需要对这些简单的类和简单的方法进行测试,显得十分冗余和无聊。

当然可以配置exclude掉这些类,不进行覆盖率的校验,但这也不是一个好办法,实际上,这些类有的时候也是应该被测试的。

幸好,有开源的类库解决了这个问题:pojo.pl

2 用代码说话

引入依赖:

<dependency>
  <groupId>pl.pojo</groupId>
  <artifactId>pojo-tester</artifactId>
  <version>0.7.6</version>
</dependency>

对于的Pojo类如下(省略方法):

public class Student {
    private String name;
    private Integer age;
    private Long classId;
    private List<String> subjects;
  //省略方法
}

public class Teacher {
    private String name;
    private Integer age;
    private List<Long> classIds;
  //省略方法
}

@Data
public class Classroom {
    private Integer id;
    private String building;
}

使用pl.pojo来快速测试如下:

//测试所有方法
@Test
public void pojoTest() {
  assertPojoMethodsForAll(Student.class, Teacher.class)
    .quickly()
    .areWellImplemented();
}

//测试特定方法
@Test
public void pojoMethodTest() {
  assertPojoMethodsForAll(Student.class, Teacher.class)
    .quickly()
    .testing(Method.CONSTRUCTOR)
    .testing(Method.GETTER)
    .testing(Method.SETTER)
    .areWellImplemented();
}

//测试被lombok注解的类也可以
@Test
public void lombokClassTest() {
  assertPojoMethodsForAll(Classroom.class)
    .areWellImplemented();
}

执行测试,查看结果,完美地提升覆盖率,只用几行代码就搞定了:

代码请查看:https://github.com/LarryDpk/pkslow-samples


欢迎关注微信公众号<南瓜慢说>,将持续为你更新...

推荐阅读:
如何制定切实可行的计划并好好执行
容器技术(Docker-Kubernetes)
SpringBoot-Cloud相关
Https专题


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK