【发布时间】:2017-10-04 17:37:44
【问题描述】:
我对 mockito 方法有疑问:when(...)。当我测试时:
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);
}}
【问题讨论】:
标签: spring testing model-view-controller junit mockito