Mock静态方法以及静态void方法
mock某个类的静态方法,需要注意的是,如果该方法在当前单元测试中被多个方法使用,需要注意关闭旧的模拟
@Test
void queryPage() {
MockedStatic<SystemContext> systemContextMockedStatic = null;
try {
systemContextMockedStatic = Mockito.mockStatic(SystemContext.class);
systemContextMockedStatic.when(() -> SystemContext.getCurrentUser()).thenReturn(mockUserInfo());
//mock 静态无返回值方法
redisUtilMockedStatic.when(()->RedisUtil.set(any(),any())).thenAnswer((Answer<Void>) invocation -> null);
//做其他的业务模拟,以及验证
} finally {
//调用静态方法完成后关闭当前模拟
systemContextMockedStatic.close();
}
}
@Value注解读取配置的属性
通过ReflectionTestUtils工具类,在初始化时添加类属性值
public class TestConfig{
@Value("${endpoint}")
private String endpoint;
@Value("${bucket}")
private String bucket;
}
@SpringBootTest
class serviceTest {
@InjectMocks
Service service;
@Mock
TestConfig testConfig;
@BeforeEach()
public void init() {
ReflectionTestUtils.setField(testConfig, "endpoint", "http://tendpointst");
ReflectionTestUtils.setField(testConfig, "bucket", "/bucket/");
}
}
MyBatisPlus 相关单测注意点
如果service类继承了 MyBatisPlus ----- ServiceImpl<M extends BaseMapper<T>, T>
类似于批量创建、更新等接口
注意:如果类中使用baseMapper,用@Autowired注入。将下属方法改成baseMapper方便测试
TService spy = Mockito.spy(tService);
//通过spy
Mockito.doReturn(true).when(spy).saveBatch(Mockito.any());
//需要注意的是最后调用的是spy对象,如果用@InjectMocks会调用真实场景
Assertions.assertDoesNotThrow(() -> spy.test(mockPOList1(), a));
异常验证
assertThatThrownBy(()->projectManageService.save(projectManageRO2)).isInstanceOf(CodedException.class);