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