J'ai un problème avec la méthode mockito: quand (...). Quand je test:Méthode quand() de Mockito ne fonctionne pas correctement
afterThrowExceptionShouldReturnCorrectHttpStatus()
Ran premier, puis le second test:
controllerShouldReturnListOfAnns()
Il échoue toujours parce qu'il jette NotFoundException. Lorsque je supprime le premier test ou exécute le deuxième test en premier, tout est correct. Cela ressemble à la méthode quand() à partir de la première méthode de remplacement de test quand() forme le second test Il y a un code de test et une configuration de test.
@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);
}}
Cela fonctionne! Je vous remercie! BTW pourquoi ce problème se produit? Est-il normal d'ajouter toujours cette méthode (@After)? – destro1
Le cycle de vie de vos tests printaniers est contrôlé par Spring Runner. Le coureur de printemps ne s'occupe pas du cycle de vie de Mockito. Vous devez donc gérer vous-même – fiddels