spring-启动测试:@get 请求 returns 正文为空

spring-boot test: @get request returns with body null

虽然响应状态为 200,但在响应正文中进行内容协商测试时模拟 GET returns 为 null。

java.lang.AssertionError: Response header 'Content-Type' 
Expected :application/json;charset=UTF-8
Actual   :null

这里是完整的测试 class 代码。我想验证内容类型是 json.

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

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    Controller controller;

    @Test
    public void test() throws Exception {
        mockMvc.perform(get("/query?mediaType=json"))
                .andExpect(status().isOk())
                .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE));
    }}

这是我的控制器端点。

    @RestController
    public class Controller {

        @RequestMapping(value = "/query", produces = {"application/json", "application/xml"}, method = RequestMethod.GET)
        public @ResponseBody ResultSet getResults(
                final HttpServletRequest request
        ) throws Throwable {

       // logic  ...
       SearchService search = (SearchService) context.getBean("search");
       ResultSet result = search.getResults();
       return result;
    }

有没有想过为什么 Body 会 return 为 null?

问题出在您的测试 class 中的控制器定义上。当您测试 Controller 时,您应该使用它的实际实例。获取此 ControllermockMvc 实例,如下所示(您可以在 @Before 带注释的设置方法中完成):

mockMvc = MockMvcBuilders.standaloneSetup(new Controller()).build();