进大厂必须要会的单元测试

x33g5p2x  于9个月前 转载在 其他  
字(4.6k)|赞(0)|评价(0)|浏览(1324)

本文将按照如下顺序给大家简单讲讲单元测试应该怎么写

什么是单元测试

单元测试又称模块测试,是针对软件设计的最小单位(模块)就行正确性的校验的测试,检查每个程序模块是否实现了规定的功能,保证其正常工作。

测试的重点:系统模块、方法的逻辑正确性

和集成测试不同,单元测试应该具备如下特点:

  1. 尽可能简短不重复
  2. 执行速度快,因为单元测试几乎可以一直运行,所以对于一些数据库、文件操作等一定要加快速度,可以采用mock的方式
  3. 具有100%的确定性,不能某几次可以执行成功,某几次执行失败

我们在企业开发中,很多大公司都是要求单测到达一定的比率才能提交代码,单测能够保证我们写的逻辑代码符合我们的预期,并且在后续的维护中都能通过单测来验证我们的修改有没有把原有的代码逻辑改错。

虽然会花费我们额外10%的时间去做单测,但是收益率还是值得的,作为一个开发,我认为我们本就该进行完整的自测后才移交给测试同学。

单元测试入门

先写一个简单的单测例子:测试一个求两个set集合交集的方法

  1. 引入依赖
  1. <dependency>
  2. <groupId>org.mockito</groupId>
  3. <artifactId>mockito-core</artifactId>
  4. <version>4.3.1</version>
  5. <scope>test</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.junit.jupiter</groupId>
  9. <artifactId>junit-jupiter</artifactId>
  10. <version>5.8.2</version>
  11. <scope>test</scope>
  12. </dependency>
  1. 被测试方法
  1. /**
  2. * 获取交集
  3. * @param set1
  4. * @param set2
  5. * @return
  6. */
  7. public Set<Integer> getIntersection(Set<Integer> set1,Set<Integer> set2){
  8. set1.retainAll(set2);
  9. return set2;
  10. }
  1. 生成测试方法

我们可以通过IDEA的自动生成功能来生成测试方法

它会在test目录下的同包名下生成一个测试类

  1. 我们编写测试逻辑
  1. class HelloServiceTest {
  2. @Test
  3. void getIntersection() {
  4. //生成mock类
  5. HelloService helloService = Mockito.mock(HelloService.class);
  6. //调用mock类的getIntersection方法时调用真实方法
  7. Mockito.when(helloService.getIntersection(Mockito.anySet(),Mockito.anySet())).thenCallRealMethod();
  8. Set<Integer> set1=new HashSet<>();
  9. set1.add(1);
  10. set1.add(2);
  11. set1.add(3);
  12. Set<Integer> set2=new HashSet<>();
  13. set2.add(5);
  14. set2.add(4);
  15. set2.add(3);
  16. Set<Integer> intersection = helloService.getIntersection(set1, set2);
  17. Set<Integer> set3=new HashSet<>();
  18. set3.add(3);
  19. //断言,判断方法结果是否和我们预想的一致
  20. Assertions.assertEquals(intersection,set3);
  21. }
  22. }
  1. 运行

运行结果:

运行完后发现断言异常,这样就能检查出我们之前写的代码不对,去检查了下,发现了问题,改正代码后重试。

  1. public Set<Integer> getIntersection(Set<Integer> set1,Set<Integer> set2){
  2. set1.retainAll(set2);
  3. return set1;
  4. }

常用方法

构建测试对象

  1. mock方法
  • 方法1
  1. HelloService helloService = Mockito.mock(HelloService.class);
  • 方法2:
    使用注解
  1. @Mock
  2. private HelloService helloService;
  3. @Test
  4. void getIntersection() {
  5. //使用@Mock,需要加下面这行代码
  6. MockitoAnnotations.openMocks(this);
  7. Mockito.when(helloService.getIntersection(Mockito.anySet(),Mockito.anySet())).thenCallRealMethod();
  8. ...
  9. }

mock出来的对象,要指定方法的返回,否则只是返回默认值,不会执行真正的方法的实现。

  1. 直接使用new 方法构建对象
  1. HelloService helloService = new HelloService();
  1. 使用@Spy注解
  1. @Spy
  2. private HelloService helloService;

使用@Spy注解的对象,在执行的时候会调用真实的方法。

上面都是简单的一级对象的构建,如果被测试的对象里面还要对象依赖怎么办呢?

构建依赖的测试对象

如这个方法:

  1. @Setter
  2. public class HelloService {
  3. private HelloDao helloDao;
  4. public String hello(){
  5. return helloDao.hello()+" xiaowang";
  6. }
  7. }
  1. mock + set
  1. HelloService helloService=new HelloService();
  2. HelloDao helloDao = Mockito.mock(HelloDao.class);
  3. helloService.setHelloDao(helloDao);
  1. @InjectMocks

使用@InjectMocks可以将mock出的依赖对象注入到它标注的测试对象中

  1. @InjectMocks
  2. private HelloService helloService;
  3. @Mock
  4. private HelloDao helloDao;

上面的例子中,将helloDao注入到了helloService中

构建静态对象

需要修改依赖

  1. <!-- <dependency>-->
  2. <!-- <groupId>org.mockito</groupId>-->
  3. <!-- <artifactId>mockito-core</artifactId>-->
  4. <!-- <version>4.3.1</version>-->
  5. <!-- <scope>test</scope>-->
  6. <!-- </dependency>-->
  7. <dependency>
  8. <groupId>org.mockito</groupId>
  9. <artifactId>mockito-inline</artifactId>
  10. <version>4.3.1</version>
  11. <scope>test</scope>
  12. </dependency>
  1. MockedStatic<JsonUtils> tMockedStatic = Mockito.mockStatic(JsonUtils.class);

因为静态方法mock了之后,在整个线程中都是生效的,如果需要隔离的话,可以使用try-with-resources来写。

区别如下:

行为规定(打桩)

接下来我们学习方法的行为规定,因为mock出来的对象默认是不执行真实方法的,需要我们指定。

  1. doReturn
  1. Mockito.doReturn("hello").when(helloDao).hello();
  1. thenReturn
  1. Mockito.when(helloDao.hello()).thenReturn("hello");
  1. thenAnswer

这种方式可以灵活的返回,比如根据参数的不同返回不同的值

  1. Mockito.when(helloDao.hello(Mockito.anyString())).thenAnswer( invocation->{
  2. String param = invocation.getArgument(0);
  3. if(param.equals("w")){
  4. return "wang";
  5. }else {
  6. return "li";
  7. }
  8. });
  1. mock异常

有时候需要测试方法异常的时候对整个方法体的影响

  1. Mockito.when(helloDao.hello(Mockito.anyString())).thenThrow(NullPointerException.class);

断言

我们执行完测试方法后,就需要对结果进行验证比对,来证明我们的方法的正确性。

  1. Assertions.assertEquals
  1. Assertions.assertEquals(hello,"hello xiaowang");
  1. Assertions.assertTrue
  1. Assertions.assertTrue(hello.equals("hello xiaowang"));
  1. Assertions.assertThrows

异常断言,判断是否是预期的异常

  1. Assertions.assertThrows(NullPointerException.class,()->{
  2. helloDao.hello();
  3. });
  1. 使用Verify断言执行次数
  1. Mockito.verify(helloDao,Mockito.times(1)).hello();

番外

另外还有两个注解,@BeforeEach和@AfterEach,顾名思义,一个是在test方法执行前执行,一个是在test方法执行后执行。

  1. @BeforeEach
  2. public void before(){
  3. System.out.println("before");
  4. }
  5. @AfterEach
  6. public void after(){
  7. System.out.println("after");
  8. }

另外推荐两款比较好用的单测生成插件 TestMe 和Diffblue

书山有路勤为径,学海无涯苦作舟

相关文章