【问题标题】:unit test Spring MissingServletRequestParameterException JSON response单元测试 Spring MissingServletRequestParameterException JSON 响应
【发布时间】:2015-07-22 14:40:39
【问题描述】:

我在 Spring 引导休息控制器中有 POST 方法,如下所示

@RequestMapping(value="/post/action/bookmark", method=RequestMethod.POST)
public @ResponseBody Map<String, String> bookmarkPost(
        @RequestParam(value="actionType",required=true) String actionType,
        @RequestParam(value="postId",required=true) String postId,
        @CurrentUser User user) throws Exception{
    return service.bookmarkPost(postId, actionType, user);
}

现在,如果我在 Postman 中使用缺少的参数进行测试,我会得到一个 400 http 响应和一个 JSON 正文:

{
  "timestamp": "2015-07-20",
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
  "message": "Required String parameter 'actionType' is not present",
  "path": "/post/action/bookmark"
}

到目前为止还可以,但是当我尝试进行单元测试时,我没有收到 JSON 响应

@Test
public void bookmarkMissingActionTypeParam() throws Exception{
    // @formatter:off
    mockMvc.perform(
                post("/post/action/bookmark")
                    .accept(MediaType.APPLICATION_JSON)
                    .param("postId", "55ab8831036437e96e8250b6")
                    )
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.exception", containsString("MissingServletRequestParameterException")));
    // @formatter:on
}

测试失败并产生

java.lang.IllegalArgumentException: json can not be null or empty

我做了一个.andDo(print()),发现响应中没有body

MockHttpServletResponse:
          Status = 400
   Error message = Required String parameter 'actionType' is not present
         Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store], Pragma=[no-cache], Expires=[1], X-Frame-Options=[DENY]}
    Content type = null
            Body = 
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

为什么我在对控制器进行单元测试时没有收到 JSON 响应,但在使用 Postman 或 cUrl 进行手动测试时却收到了它?

编辑:我添加了 @WebIntegrationTest 但得到了同样的错误:

import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.MediaType;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RestApplication.class)
@WebIntegrationTest
public class PostControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                .addFilter(springSecurityFilterChain)
                .build();
    }  

    @Test
    public void bookmarkMissingActionTypeParam() throws Exception{
        // @formatter:off
        mockMvc.perform(
                    post("/post/action/bookmark")
                        .accept(MediaType.APPLICATION_JSON)
                        .param("postId", "55ab8831036437e96e8250b6")
                        )
                .andDo(print())
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$.exception", containsString("MissingServletRequestParameterException")));
        // @formatter:on
    }
}

【问题讨论】:

  • 我也遇到了同样的问题,但没有错误响应:你有什么成功的吗?
  • 不,还没有……我跳过了这些案例的测试!

标签: java spring-boot spring-test-mvc spring-restcontroller jsonresponse


【解决方案1】:

这是因为 Spring Boot 自动配置了一个异常处理程序 org.springframework.boot.autoconfigure.web.BasicErrorController,它可能不存在于您的单元测试中。获得它的一种方法是使用 Spring Boot 测试支持相关的注释:

@SpringApplicationConfiguration
@WebIntegrationTest

更多详情here

更新: 您是绝对正确的,UI 与测试中的行为非常不同,响应状态代码的错误页面在非 servlet 测试环境中没有正确连接。改进此行为可能是为 Spring MVC 和/或 Spring Boot 打开的一个很好的错误。

目前,我有一个解决方法,可以通过以下方式模拟 BasicErrorController 的行为:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {RestApplication.class, TestConfiguration.class})
@WebIntegrationTest
public class PostControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                .addFilter(springSecurityFilterChain)
                .build();
    }  

    @Test
    public void bookmarkMissingActionTypeParam() throws Exception{
        // @formatter:off
        mockMvc.perform(
                    post("/post/action/bookmark")
                        .accept(MediaType.APPLICATION_JSON)
                        .param("postId", "55ab8831036437e96e8250b6")
                        )
                .andDo(print())
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$.exception", containsString("MissingServletRequestParameterException")));
        // @formatter:on
    }
}
     @Configuration
    public static class TestConfiguration {


        @Bean
        public ErrorController errorController(ErrorAttributes errorAttributes) {
            return new ErrorController(errorAttributes);
        }
    }
@ControllerAdvice
class ErrorController extends BasicErrorController {

    public ErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @Override
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        return super.error(request);
    }
}

我在这里做的是添加一个ControllerAdvice,它处理异常流并将委托回BasicErrorController。这至少会使您的行为保持一致。

【讨论】:

  • 我添加了 @WebIntegrationTest 但得到了同样的错误,我在上面添加了完整的测试类
  • 仅供参考,您的RestApplication 是否有@EnableAutoConfiguration 注释。
  • 不,只使用 '@SpringBootApplication' .. 不是等价的吗?
  • 你说得对,我已经添加了一个潜在解决方法的更新
  • 我面临同样的问题,但仍未解决
【解决方案2】:

最初,它应该在定义 REST 控制器方法时通过 @ResponseBody 标签修复错误。它将修复测试类中的 json 错误。 但是,当您使用 Spring Boot 时,您将使用 @RestController 定义控制器类,它应该自动处理错误而不定义 @Controller@ResponseType 标签。

【讨论】:

  • 我面临同样的问题,这个答案没有帮助,@Biju 以正确的方式理解他们的问题。
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-11
  • 2018-06-04
相关资源
最近更新 更多