[英]doThrow Exception not throwing for spring MVC unit test?
我试过切换到 when() 并得到编译器错误
我在同一个项目的另一个测试中成功使用了 doThrow(...),所以我不知道这里发生了什么
单元测试代码:
doThrow(new Exception("the client cancelled the request, ya dingus!")).when(handler).write(any());
MvcResult result = mockMvc.perform(post("/myPath")
.content(String.valueOf(mockValidRequest))
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("utf-8"))
.andExpect(status().is5xxServerError())
.andReturn();
我正在测试的代码(/myPath 的处理程序方法):
@PostMapping("/myPath")
public ResponseEntity<String> handleRequest(@RequestBody MyPojo request) {
try {
handler.write(request);
} catch (Exception e) {
return new ResponseEntity<>("Exception thrown during event processing: " + e, HttpStatus.SERVICE_UNAVAILABLE);
}
return new ResponseEntity<>("Success", HttpStatus.OK)
}
问题是测试说实际结果是 200 成功,当应该捕获异常时,服务不可用 5xx 响应。
我发现我可以让测试通过直接调用函数......看起来 MockMvc 没有包含 doThrow 逻辑
修改后的单元测试:
doThrow(new Exception("some error")).when(handler).sendToSqsWriter(any());
ResponseEntity<String> response = controller.handleRequest(new Gson().fromJson(new JSONObject(mockApptRequestBody);.toString(), SeamAppointmentRequest.class));
assertTrue(response.toString().contains("some error"));
assertTrue(response.getStatusCodeValue() == 503);
所有 json/gson jazz 都在解决运行时解析错误
所以我找到了我的问题的正确答案:
我的原始帖子中没有这个片段,但是handler
在测试中被实例化,如下所示:
@Mock
EventHandler handler;
它必须是:
@MockBean
EventHandler handler;
我的猜测是因为@MockBean
是 spring 模拟,而@Mock
来自 Mockito,它可能是在模拟在 Spring 容器之外实例化的事件处理程序。 因此,为什么我不认为它是在捡起 doThrow ......它确实捡到了它,但监视了错误的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.