单元测试Mockito使用心得2

背景

前面,我们已经接入了mockito,但是上个版本的单元测试需要接入的测试中间件太多了,本次做了一次缩减,删掉其他测试中间件,只保留最原始的mockito与springframework Test。

使用

1. 添加依赖

<dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <scope>test</scope>
</dependency>
 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
   </dependency>

2. 具体使用

  1. @MockBean修饰需要测试的类
  2. 声明调用特定方法时,传入指定参数,返回指定指
    • when(xxx.yyy(zzz)).thenReturn(aaa); // 当调用xxx.yyy()方法且入参是zzz时,返回aaa;如果入参不是zzz,则返回null。
    • when(xxx.yyy()).thenAnswer(t -> {});// 当调用xxx.yyy()方法时,没有返回值,执行一个自定义的函数体。
  3. test原本需要测试的方法

例:

service调用链:

@Service
@AllArgsConstructor
public class MockService {
    
    private final UserReferenceService userReferenceService;

    public long testMockMethod(Long userId) {
        if (userId < 0) {
            return -1;
        }
        return userReferenceService.getUserByUserId(userId).getUserId();
    }

}

单元测试使用:

@ActiveProfiles("dev")
@SpringBootTest
class MockServiceTest {

    // 需要测试的类
    @Autowired
    private MockService mockService;

    // 需要mock的类
    @MockBean
    private UserReferenceService userReferenceService;


    @Test
    void testMockMethod() {

        // 当传入-1, 返回100
         Mockito.when(userReferenceService.getUserByUserId(-1L))
                 .thenReturn(UserBaseInfoVO.builder().userId(100L).build());

        // 当传入-2, 返回200
         Mockito.when(userReferenceService.getUserByUserId(-2L))
                 .thenReturn(UserBaseInfoVO.builder().userId(200L).build());

        long o1 = mockService.testMockMethod(-1L);
        Assert.assertEquals("比较错误", 100L, o1);

        long o2 = mockService.testMockMethod(-2L);
        Assert.assertEquals("比较错误", 200L, o2);

    }
}
 

使用起来比之前集成的更加简单。

以上。