I can not pass the test with MockMvc in my Spring Boot application.
My ControllerAdvice looks like:
@ControllerAdvice
@Slf4j
public class ExceptionHandlers extends BaseExceptionHandler {
public ExceptionHandlers() {
super(log);
}
@ResponseBody
@ExceptionHandler(RunNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleRunNotFoundController(final RunNotFoundException ex) {
log.error("Run not found thrown", ex);
return new ErrorResponse(LocalDateTime.now(), "RUN_NOT_FOUND", ex.getMessage(), HttpStatus.NOT_FOUND.value());
}
}
and I have two test :
@RunWith(SpringRunner.class)
@WebMvcTest(RunController.class)
public class RunControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private RunService runService;
// @Before
// public void setup() {
// this.mvc = MockMvcBuilders.standaloneSetup(runService)
// .setControllerAdvice(new ExceptionHandlers())
// .build();
// }
@Test
public void getRunsTestCorrectValues() throws Exception {
List<Run> list = prepareRunList();
when(runService.getRuns()).thenReturn(list);
mvc.perform(get("/api/runs")
.contentType("application/json"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0]").exists())
.andExpect(jsonPath("$[0]").isNotEmpty())
.andExpect(jsonPath("$[0].id").value(1))
}
@Test
public void getRunsTestRunsNotFoundException() throws Exception {
given(runService.getRuns()).willReturn(Collections.emptyList());
mvc.perform(get("/api/runs")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isNotFound());
}
}
In this case when I have setup()
commented test getRunsTestCorrectValues()
passed and getRunsTestRunsNotFoundException()
failed with:
In second case when I will uncomment setup()
and re-run test I got getRunsTestCorrectValues()
failed and getRunsTestRunsNotFoundException()
passed with:
I think is something related with setup()
. Does someone has any ideas?