我无法在 Spring Boot 应用程序中通过 MockMvc 测试。
我的 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()
失败时:
在第二种情况下,当我取消注释 setup()
并重新运行测试时,我得到 getRunsTestCorrectValues()
失败,而 getRunsTestRunsNotFoundException()
通过与:
我认为与setup()
有关。有人有什么想法吗?
最佳答案
当您 mock runService 时,您应该简单地保留您的测试用例, 所以你应该像这样修改第二个,以便抛出异常。
given(runService.getRuns()).willThrow(new RunNotFoundException("Not Found"));
关于java - 使用 MockMvc Http Status 错误测试 @ControllerAdvice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61307129/