mercredi 4 octobre 2017

Method when() from Mockito do not work correctly

i have problem with mockito method: when(...). When test:

afterThrowExceptionShouldReturnCorrectHttpStatus()

ran first, then the second test:

controllerShouldReturnListOfAnns()

always fails because throw NotFoundException. But when i delete the first test or running second test as first, then everything is correct. This look like method when() from first test override method when() form the second test There is test code and test configuration.

@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)));
}}

Config:

@Profile("dev")
@Configuration
public class BeanConfig {


@Bean
public CommentsRepo commentsRepo() {
    return mock(CommentsRepo.class);
}}

Aucun commentaire:

Enregistrer un commentaire