Spring Boot集成测试以空主体响应-MockMvc [英] Spring Boot integration test responding with empty body - MockMvc

查看:162
本文介绍了Spring Boot集成测试以空主体响应-MockMvc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到与此类似的问题,但是我还没有找到适合我的解决方案,因此我希望将其发布并提供足够的细节来解决.

所以我有以下课程:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestController {

    @Mock
    private Controller controller;

    private MockMvc mockMvc;

    @InjectMocks
    private SearchService service;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(controller).setControllerAdvice(new GlobalExceptionHandler()).build();
    }

    @Test
    public void getSearchResults() throws Exception{
        this.mockMvc.perform(post("/something/search").header("header1","1").header("header2","2")
            .content("MY VALID JSON REQUEST HERE")
            .contentType(MediaType.APPLICATION_JSON)).andDo(print());
    }
}

上面的代码打印:

MockHttpServletRequest:
    HTTP Method = POST
    Request URI = /something/search
     Parameters = {}
      Headers = {Content-Type=[application/json], header1=[1], header2=[2]}

Handler:
    Type = com.company.controller.Controller
    Method = public org.springframework.http.ResponseEntity<com.company.SearchResponse> com.company.controller.Controller.getSearchResults(com.company.SearchRequest,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.io.IOException

Async:
    Async started = false
     Async result = null

Resolved Exception:
    Type = null

ModelAndView:
    View name = null
    View = null
    Model = null

FlashMap:
    Attributes = null

MockHttpServletResponse:
            Status = 200
     Error Message = null
           Headers = {}
      Content type = null
              Body = 
     Forwarded URL = null
    Redirected URL = null
           Cookies = []

即使我尝试搜索的数据在我的本地弹性服务器中不可用(它是),它也应返回带有"{}"的正文,而不仅仅是空的.因此,我对它为什么建立连接并返回状态200感到困惑.

这是我的控制器类:

@CrossOrigin
@RestController
@RequestMapping(value = "/something")
@Api("search")
@Path("/something")
@Produces({"application/json"})
@Consumes({"application/json"})
public class Controller {

    @Autowired
    private SearchService searchService;

    @POST
    @PATH("/search")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    @RequestMapping(value = "/search", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<SearchResponse> getSearchResults(
        @ApiParam(value = "json string with required data", required = true) @Valid @RequestBody SearchRequest request,
        @RequestHeader(required = true) @ApiParam(value = "header1", required = true) @HeaderParam("header1") String header1,
        @RequestHeader(required = true) @ApiParam(value = "header2", required = true) @HeaderParam("header2") String header2
    ) throws IOException {
        //some logic
        return new ResponseEntity(Object, HttpStatus.OK);
    }

此外,如果我在请求中给出了不正确的值(仍然是正确的json),我将收到有效的错误响应.

感谢任何帮助的人!!! :/

解决方案

尝试此测试.该测试是根据spring boot文档进行的.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class ControllerTest {


    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private SearchService service;

    @Before
    public void setUp(){
        when(service.someMethod(any()))
                .thenReturn(SomeResponse);
    }

    @Test
    public void getSearchResults() throws Exception{
        this.mockMvc.perform(post("/something/search").header("header1","1").header("header2","2")
                .content("MY VALID JSON REQUEST HERE")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(mvcResult -> {
                    //Verrify Response here
                });
    }
}

I've seen similar questions to this, but I've yet to find a solution that works for me, so i'm posting it with hopefully enough details to resolve..

So I have the following class:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestController {

    @Mock
    private Controller controller;

    private MockMvc mockMvc;

    @InjectMocks
    private SearchService service;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(controller).setControllerAdvice(new GlobalExceptionHandler()).build();
    }

    @Test
    public void getSearchResults() throws Exception{
        this.mockMvc.perform(post("/something/search").header("header1","1").header("header2","2")
            .content("MY VALID JSON REQUEST HERE")
            .contentType(MediaType.APPLICATION_JSON)).andDo(print());
    }
}

The above code prints:

MockHttpServletRequest:
    HTTP Method = POST
    Request URI = /something/search
     Parameters = {}
      Headers = {Content-Type=[application/json], header1=[1], header2=[2]}

Handler:
    Type = com.company.controller.Controller
    Method = public org.springframework.http.ResponseEntity<com.company.SearchResponse> com.company.controller.Controller.getSearchResults(com.company.SearchRequest,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.io.IOException

Async:
    Async started = false
     Async result = null

Resolved Exception:
    Type = null

ModelAndView:
    View name = null
    View = null
    Model = null

FlashMap:
    Attributes = null

MockHttpServletResponse:
            Status = 200
     Error Message = null
           Headers = {}
      Content type = null
              Body = 
     Forwarded URL = null
    Redirected URL = null
           Cookies = []

Even if the data i'm trying to search is not available in my local elastic server (which it is), it should return the body with "{}" not just empty. So i'm a little baffled as to why it's making the connection and returning status 200.

Here's my controller class:

@CrossOrigin
@RestController
@RequestMapping(value = "/something")
@Api("search")
@Path("/something")
@Produces({"application/json"})
@Consumes({"application/json"})
public class Controller {

    @Autowired
    private SearchService searchService;

    @POST
    @PATH("/search")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    @RequestMapping(value = "/search", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<SearchResponse> getSearchResults(
        @ApiParam(value = "json string with required data", required = true) @Valid @RequestBody SearchRequest request,
        @RequestHeader(required = true) @ApiParam(value = "header1", required = true) @HeaderParam("header1") String header1,
        @RequestHeader(required = true) @ApiParam(value = "header2", required = true) @HeaderParam("header2") String header2
    ) throws IOException {
        //some logic
        return new ResponseEntity(Object, HttpStatus.OK);
    }

Also, if I give some improper values in the request (still proper json), I will receive the valid error responses.. A little peculiar.

Thanks for anyone who helps!!! :/

解决方案

Try with this test. This test is as per spring boot documentation.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class ControllerTest {


    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private SearchService service;

    @Before
    public void setUp(){
        when(service.someMethod(any()))
                .thenReturn(SomeResponse);
    }

    @Test
    public void getSearchResults() throws Exception{
        this.mockMvc.perform(post("/something/search").header("header1","1").header("header2","2")
                .content("MY VALID JSON REQUEST HERE")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(mvcResult -> {
                    //Verrify Response here
                });
    }
}

这篇关于Spring Boot集成测试以空主体响应-MockMvc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆