简体   繁体   English

为 spring MVC 单元测试不抛出 doThrow 异常?

[英]doThrow Exception not throwing for spring MVC unit test?

ive tried switch to a when() and get compiler errors我试过切换到 when() 并得到编译器错误

i have successfully used doThrow(...) in another test in the same project, so i dont know whats going on here我在同一个项目的另一个测试中成功使用了 doThrow(...),所以我不知道这里发生了什么

Unit test code:单元测试代码:

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();

Code I am testing (handler method for /myPath):我正在测试的代码(/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)
}

The problem is the test says the actual result is a 200 success, when there should have been an exception caught, and a service unavailable 5xx response.问题是测试说实际结果是 200 成功,当应该捕获异常时,服务不可用 5xx 响应。

i found that i could get the tests to pass calling the function directly ... it just seems like MockMvc is not incorporating the doThrow logic我发现我可以让测试通过直接调用函数......看起来 MockMvc 没有包含 doThrow 逻辑

revised unit test:修改后的单元测试:

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);

all the json/gson jazz is resolving runtime parsing errors所有 json/gson jazz 都在解决运行时解析错误

So I found the proper answer to my issue:所以我找到了我的问题的正确答案:

I didnt have this snippet in my original post, but the handler was being instantiated in the test like this:我的原始帖子中没有这个片段,但是handler在测试中被实例化,如下所示:

@Mock
EventHandler handler;

it needed to be:它必须是:

@MockBean 
EventHandler handler;

My guess is since @MockBean is the spring mock, and @Mock is from Mockito, it was probably mocking an event handler that was instantiated outside of the Spring container.我的猜测是因为@MockBean是 spring 模拟,而@Mock来自 Mockito,它可能是在模拟在 Spring 容器之外实例化的事件处理程序。 Thus why I didnt think it was picking up the doThrow ... it did pick it up, but spied on the wrong instance.因此,为什么我不认为它是在捡起 doThrow ......它确实捡到了它,但监视了错误的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM