依赖
3.8.0版本已支持mock静态类的静态方法. 但是使用上需要注意
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-inline -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
插件
静态方法
public class XxxTest {
static MockedStatic<LoginUtils> loginUtilsMockedStatic;
@BeforeClass
public static void beforeClass() throws Exception {
loginUtilsMockedStatic = mockStatic(LoginUtils.class);
loginUtilsMockedStatic.when(LoginUtils::getCompanyId).thenReturn(0L);
loginUtilsMockedStatic.when(LoginUtils::getUid).thenReturn(2);
loginUtilsMockedStatic.when(LoginUtils::getCompanyIdAndUid).thenReturn(Tuple2.of(1L, 2L));
}
@AfterClass
public static void afterClass() throws Exception {
loginUtilsMockedStatic.close();
}
}
其他问题
- dao相关需要验证sql正常,避免线上出现sql执行错误的问题。
待测试内部private方法不mock,如果要mock,可以调整为protected
- mock 父类方法
mock 当前类某些方法
public class WaitTestClassTest {
@Mock // mock外部方法的调用
Example1 example1;
@Mock
Example2 example2;
@Spy // 自己的方法, 父类的方法
@InjectMocks //待验证的class
WaitTestClass waitTestClass;
@Test
public vod testCreate(){
doReturn(true).when(waitTestClass).saveBatch(anyList());
assertTrue(waitTestClass.saveBatch(anyList()));
when(example1.getGlobalId()).thenReturn(System.currentTimeMillis());
when(example2.countRelationsByTagId(anyLong(), anyLong())).thenReturn(0);
final SingleEditDto singleEditDto = new SingleEditDto();
//setter...
waitTestClass.singleEdit(singleEditDto);
}
}