单元测试踩坑记录: 使用Mockito.when() 时mock总是不生效
@TestConfiguration
@Order
public class TestConfiguration {
public TestConfiguration() {
}
@Bean
@ConditionalOnMissingBean({ObjectMapper.class})
ObjectMapper testObjectMapper() {
return (new WebConfiguration()).objectMapper();
}
@Bean
@ConditionalOnMissingBean({ConcurrentJobExecutor.class})
ConcurrentJobExecutor testConCurrentExecutor() {
return new ConcurrentTestExecutor();
}
@Bean
@ConditionalOnMissingBean({SpringBeanUtil.class})
SpringBeanUtil testSpringBeanUtil() {
return new SpringBeanUtil();
}
@Bean
@ConditionalOnMissingBean({ConversionService.class})
public ConversionService conversionService() {
return ApplicationConversionService.getSharedInstance();
}
}
@ContextConfiguration(
initializers = {ConfigFileApplicationContextInitializer.class},
classes = {TestConfiguration.class}
)
@ExtendWith({SpringExtension.class})
@TestInstance(Lifecycle.PER_CLASS)
public class SpringTestExtension {
@Autowired
ApplicationContext ctx;
public SpringTestExtension() {
}
@BeforeAll
public void beforeAllTest() {
SpringBeanUtil.setContext(this.ctx);
}
}
@Component
public class CommonService {
public List<String> a(Integer boo, List<String> strings) {
xxxx
}
}
@Component
public class ExecuteService {
@Autowired
private CommonService commonService;
public void b() {
commonService.a();
xxx
}
}
@Import({ExecuteService.class})
class Test extends SpringTestExtension{
@Autowired
private ExecuteService executeService;
@MockBean
private CommonService commonService;
@Test
public void test() {
Mockito.when(commonService.a(any(), anyList())).thenReturn(Lists.newArrayList("test"));
}
}
(1)问题
when(commonService.a(any(), anyList())).thenReturn(Lists.newArrayList("test"))
这一行代码mock一直不生效,实际调用commonService.a()时总是返回emptyList。
(2)原因
目前Mockito.when()方法只对any()生效 ,anyList(), anyMap()作为参数时,均会返回默认结果值:emptyList, "", null等。(⚠️但是jetbrains idea默认提示时对于List<T>, Map<K, V>这种参数都是提示anyList, anyMap, 这里需要特别注意)
(3)修改:
修改为 when(commonService.a(any(), any())).thenReturn(Lists.newArrayList("test")) 后, 返回结果正常: Lists.newArrayList("test")