用空体响应的Spring Boot集成测试 - MockMvc

时间:2017-04-29 02:03:36

标签: java spring spring-boot junit integration-testing

我已经看到了与此类似的问题,但我还没有找到适合我的解决方案,所以我发布了希望足够的细节来解决这个问题。

所以我有以下课程:

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

即使我尝试搜索的数据在我的本地弹性服务器(它是)中不可用,它也应该使用&#34; {}&#34;不仅仅是空的。所以我对它为什么要建立联系并返回状态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),我将收到有效的错误响应..有点奇怪。

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

2 个答案:

答案 0 :(得分:3)

尝试此测试。此测试按照春季启动文档进行。

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

答案 1 :(得分:0)

试试下面的方法,它会让你避免每次都单独模拟每个方法:

@MockBean(answer = Answers.CALLS_REAL_METHODS)
private SearchService service;