1
我有mockito方法的问题:when(...)。当我测试:方法当()从Mockito不能正常工作
afterThrowExceptionShouldReturnCorrectHttpStatus()
然先,那么第二个测试:
controllerShouldReturnListOfAnns()
,因为它扔NotFoundException它总是失败。当我第一次删除第一个测试或第二次测试时,那么一切都是正确的。这看起来像方法when()从第一次测试重写方法when()进行第二次测试时有测试代码和测试配置。
@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
public class AnnTestController {
@Autowired
private AnnounService annSrv;
@Autowired
private AnnounRepo annRepo;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void contextLoads() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void afterThrowExceptionShouldReturnCorrectHttpStatus() throws Exception {
when(this.annRepo.getAnnounList()).thenThrow(NotFoundAnnounException.class);
this.mockMvc.perform(get("/ann/list")).andExpect(status().isNotFound());
}
@Test
public void controllerShouldReturnListOfAnns() throws Exception {
List<Announcement> lst = new ArrayList<>();
lst.add(new Announcement(1, "test", "test"));
when(annRepo.getAnnounList()).thenReturn(lst);
this.mockMvc.perform(get("/ann/list"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id", is(1)));
}}
配置:
@Profile("dev")
@Configuration
public class BeanConfig {
@Bean
public CommentsRepo commentsRepo() {
return mock(CommentsRepo.class);
}}
这是工作!谢谢!顺便说一句。为什么会出现此问题?总是添加此方法(@After)是否正常? – destro1
春季测试的生命周期由Spring Runner控制。 春季运动员不照顾Mockito生命周期。 所以你必须自己管理它 – fiddels