依赖

3.8.0版本已支持mock静态类的静态方法. 但是使用上需要注意

  1. <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
  2. <dependency>
  3. <groupId>org.mockito</groupId>
  4. <artifactId>mockito-core</artifactId>
  5. <version>3.8.0</version>
  6. <scope>test</scope>
  7. </dependency>
  8. <!-- https://mvnrepository.com/artifact/org.mockito/mockito-inline -->
  9. <dependency>
  10. <groupId>org.mockito</groupId>
  11. <artifactId>mockito-inline</artifactId>
  12. <version>3.8.0</version>
  13. <scope>test</scope>
  14. </dependency>

插件

image.png

静态方法

  1. public class XxxTest {
  2. static MockedStatic<LoginUtils> loginUtilsMockedStatic;
  3. @BeforeClass
  4. public static void beforeClass() throws Exception {
  5. loginUtilsMockedStatic = mockStatic(LoginUtils.class);
  6. loginUtilsMockedStatic.when(LoginUtils::getCompanyId).thenReturn(0L);
  7. loginUtilsMockedStatic.when(LoginUtils::getUid).thenReturn(2);
  8. loginUtilsMockedStatic.when(LoginUtils::getCompanyIdAndUid).thenReturn(Tuple2.of(1L, 2L));
  9. }
  10. @AfterClass
  11. public static void afterClass() throws Exception {
  12. loginUtilsMockedStatic.close();
  13. }
  14. }

其他问题

  • dao相关需要验证sql正常,避免线上出现sql执行错误的问题。
  • 待测试内部private方法不mock,如果要mock,可以调整为protected

    • mock 父类方法
    • mock 当前类某些方法

      1. public class WaitTestClassTest {
      2. @Mock // mock外部方法的调用
      3. Example1 example1;
      4. @Mock
      5. Example2 example2;
      6. @Spy // 自己的方法, 父类的方法
      7. @InjectMocks //待验证的class
      8. WaitTestClass waitTestClass;
      9. @Test
      10. public vod testCreate(){
      11. doReturn(true).when(waitTestClass).saveBatch(anyList());
      12. assertTrue(waitTestClass.saveBatch(anyList()));
      13. when(example1.getGlobalId()).thenReturn(System.currentTimeMillis());
      14. when(example2.countRelationsByTagId(anyLong(), anyLong())).thenReturn(0);
      15. final SingleEditDto singleEditDto = new SingleEditDto();
      16. //setter...
      17. waitTestClass.singleEdit(singleEditDto);
      18. }
      19. }