简体   繁体   English

Spring MockMvc 返回 200 而不是 201。如何调试?

[英]Spring MockMvc is returning 200 instead of a 201. How to debug?

I am attempting to test a controller with several HTTP verbs using Spring MockMvc.我正在尝试使用 Spring MockMvc 测试具有多个 HTTP 动词的控制器。 Currently GET and DELETE work as expected, but PUT and PATCH are not returning 201, when they should be.目前GETDELETE按预期工作,但PUTPATCH没有返回 201,而它们应该返回。

The PATCH controller is setup as follows: PATCH控制器设置如下:

@CustomRequestMapping(method = PATCH, value = "/{api-root}")
public ResponseEntity patch(@PathVariable(value = "api-root") String id, @RequestBody ApiRoot apiRoot) {
     return apiRootService.softUpdate(id, apiRoot);
}

The @CustomRequestMapping... annotation just sets up consumes and produces to be a particular content type. @CustomRequestMapping...注释只是将consumesproduces设置为特定的内容类型。

the softUpdate() method referenced above performs the following: softUpdate()方法执行以下操作:

public ResponseEntity softUpdate(String id, ApiRoot apiRoot) {
    if (apiRoot.getId() == null) {
        apiRoot.setId(id);
    }

    ApiRootDocument updated = softUpdate(apiRoot);
    return ResponseEntity
            .created(EscapeUtil.buildUrl(applicationProperties.getHostname(), applicationProperties.getPort(), id))
            .body(updated);
}

This is working and tested outside of the MockMvc unit tests.这是在 MockMvc 单元测试之外工作和测试的。 It correctly returns a 201 Created to Postman, with the body being the new JSON Object that was created as a result of the PATCH .它正确地将201 Created返回给 Postman,主体是作为PATCH结果创建的新 JSON 对象。

My test is setup as:我的测试设置为:

public void testPatchApiRootEndpoint() throws Exception {
    String testTitle = "New Test Title";

    // Mock the service call for softUpdate() to return 'created' in the same way that the method does
    when(apiRootService.softUpdate(TestData.apiRoot1.getId(), TestData.apiRoot1.withTitle(testTitle)))
            .thenReturn(ResponseEntity
                .created(URI.create(EscapeUtil.buildUrlString("localhost", "8001", TestData.apiRoot1.getId())))
                .body((ApiRootDocument) TestData.apiRoot1.withTitle(testTitle)));

    // Perform a patch update using a new title provided as key-value
    JsonObject titleJson = new JsonObject();
    titleJson.addProperty("title", testTitle);
    mockMvc.perform(patch("/{api-root}", TestData.apiRoot1.getId())
                .contentType(Constants.TAXII2_CONTENT_TYPE)
                .content(titleJson.toString()))
            .andExpect(status().isCreated());
}

Which results in a 200 being returned, instead of a 201 .这导致200被返回,而不是201 I'm really confused, and it has been difficult to research.我真的很困惑,一直很难研究。 Most similar issues are finding 4XX response codes when they expect 2XX, and the solution is typically something to do with the setup of the request.大多数类似的问题是在他们期望 2XX 时找到 4XX 响应代码,解决方案通常与请求的设置有关。

The only interesting logs I can seem to find are:我似乎能找到的唯一有趣的日志是:

09:48:25.064 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Servlet '' configured successfully
09:48:25.208 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - DispatcherServlet with name '' processing PATCH request for [/api-root-1]
09:48:25.211 [main] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Looking up handler method for path /api-root-1
09:48:25.219 [main] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Returning handler method [public org.springframework.http.ResponseEntity xor.bcmc.flarecloud.apiroot.controller.ApiRootController.patch(java.lang.String,xor.bcmc.taxii2.resources.ApiRoot)]
09:48:25.388 [main] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Read [class xor.bcmc.taxii2.resources.ApiRoot] as "application/vnd.oasis.taxii+json;version=2.0" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@20921b9b]
09:48:25.428 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Null ModelAndView returned to DispatcherServlet with name '': assuming HandlerAdapter completed request handling
09:48:25.428 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request

Looks like your mocked call not worked.看起来您的模拟电话无效。 You can easily check if you replace values to the any():您可以轻松检查是否将值替换为 any():

when(apiRootService.softUpdate(Mockito.any(), Mockito.any())
.thenReturn(ResponseEntity
                .created(URI.create(EscapeUtil.buildUrlString("localhost", "8001", TestData.apiRoot1.getId())))
                .body((ApiRootDocument) TestData.apiRoot1.withTitle(testTitle)));

I just checked if you use wrong mock from controller is returned 200 status, but if mock is correct i got 201.我刚刚检查了您是否使用了错误的控制器模拟返回 200 状态,但如果模拟正确,我得到 201。

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

相关问题 Spring 引导 MockMVC 在单元测试时返回空体,状态码为 200 - Spring Boot MockMVC returning empty body with statuscode 200 when unit testing 与responseEntity问题。 即使ResponseEntity.HttpStatus为201,MockMvc.Perform()也会提供200个状态代码 - Issue with responseEntity . MockMvc.Perform() gives 200 status code even if the ResponseEntity.HttpStatus is 201 Spring API REST Controller 在 POST 方法后返回 HTTP 406 而不是 HTTP 201 - Spring API REST Controller returning HTTP 406 instead of HTTP 201 after POST method Spring MVC Mockito 测试返回 406 错误而不是 200 - Spring MVC Mockito Test returning 406 error instead of 200 Spring 安全返回 200 而不是 401,如 HttpWebHandlerAdapter 所述 - Spring Security returning 200 instead of 401 as stated by HttpWebHandlerAdapter 春季启动:MockMvc返回奇怪的响应 - Spring Boot: MockMvc returning strange responses 如何在 Spring 5 中创建 MockMvc 和 WebDriver - How to create a MockMvc and a WebDriver in Spring 5 如何在 Spring Boot 中注入 MockMvc? - How to inject MockMvc in Spring Boot? 在Spring Boot中测试Rest API时,Spring Test返回404而不是200 - Spring Test returning 404 instead of 200 in testing Rest API in Spring Boot MockMvc 抛出 HttpMediaTypeNotSupportedException 预期状态:201 但为 415 - MockMvc throws HttpMediaTypeNotSupportedException Status expected: 201 but was 415
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM