【问题标题】:spring-boot test: @get request returns with body nullspring-boot 测试:@get 请求返回正文为空
【发布时间】:2019-07-29 12:01:44
【问题描述】:

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

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

这里是完整的测试类代码。我想验证内容类型是 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 会返回 null 吗?

【问题讨论】:

    标签: rest spring-boot spring-boot-test content-negotiation


    【解决方案1】:

    问题在于您的测试类中的控制器定义。在测试Controller 时,您应该使用它的实际实例。为这个Controller 获取mockMvc 实例,如下所示(您可以在@Before 带注释的设置方法中执行此操作):

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

    【讨论】:

    • 对于这个,我遇到了异常:java.lang.AssertionError: Content type not set
    • 改变了我的答案。请立即检查。
    • 好的,这需要我注入一些我在 Controller 类中的模拟对象,但这最终奏效了。我注意到@InjectMocks Controller controller 的结果相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2020-09-02
    • 2021-08-06
    • 2020-10-26
    • 2021-07-14
    • 2021-10-16
    • 2015-11-14
    相关资源
    最近更新 更多