Unit test Spring MissingServletRequestParameterException JSON Response

I have a POST method in a Spring boot controller as follows

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

now, if I test with a missing parameter in Postman, I get a 400 http response and a JSON body:

{
  "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"
}

so far this is fine, but when I try unit test, I don't get the JSON response back

@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
}

the test fails and produces

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

I did .andDo (print ()) and found that there is no body in the answer

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 = []

why don't I get a JSON response while testing my controller, but get it in manual testing using Postman or cUrl?

EDIT: I added @WebIntegrationTest, but got the same error:

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
    }
}
+4
source share
2 answers

, Spring Boot org.springframework.boot.autoconfigure.web.BasicErrorController, , , . Spring :

@SpringApplicationConfiguration
@WebIntegrationTest

: , , , , . Spring MVC / Spring .

, 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, Exception BasicErrorController. , , .

+2

@ResponseBody REST. json . spring, @RestController, @Controller @ResponseType.

0

Source: https://habr.com/ru/post/1599115/


All Articles