Я не могу пройти тест с Mock Mvc в моем приложении Spring Boot.
Мой ControllerAdvice выглядит так:
@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());
}
}
, и у меня есть два теста:
@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());
}
}
В этом случае, когда я setup()
прокомментировал тест getRunsTestCorrectValues()
, пройденный и getRunsTestRunsNotFoundException()
не удалось с:
![enter image description here](https://i.stack.imgur.com/0W2Ov.png)
Во втором случае, когда я раскомментирую setup()
и перезапущу тест, я получил getRunsTestCorrectValues()
, и неудача и getRunsTestRunsNotFoundException()
передано с:
![enter image description here](https://i.stack.imgur.com/VwMZa.png)
Я думаю, что-то связано с setup()
. У кого-нибудь есть идеи?