415 MockMvc 测试中不支持的媒体类型

问题描述 投票:0回答:1

我在尝试测试我的 @Controller 的方法之一时收到 415 错误。 这是我的代码。

测试班:

@SpringBootTest(classes = APIController.class)
@AutoConfigureMockMvc
class APIControllerTest {

    @MockBean
    private ListifyService listifyService;

    @Autowired
    private MockMvc mvc;

    @Test
    void loginTest() throws Exception {
        when(listifyService.login(anyString(), anyString())).thenReturn("aless");

        String url = "/API/login";

        String requestJson = "{" +
                "\"email\":\"[email protected]\"," +
                "\"password\":\"password\"" +
                "}";

        mvc.perform(post(url)
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .characterEncoding("UTF-8") //if i remove this instruction, the body won't be send (empty body in test log)
                    .content(requestJson))
                    .andDo(print())
                    .andExpect(status().isOk());
    }
}

控制器方法:

@PostMapping(value="/API/login", consumes = {"application/json"}, produces = {"application/json"})
public ResponseEntity<String> login(HttpSession session, @RequestBody Map<String, String> body) {
    System.out.println("here");
    String username = listifyService.login(body.get("email"), body.get("password"));
    if (username != null) {
        session.setAttribute("username", username);
        return ResponseEntity.ok().body(username);
    } else {
        return ResponseEntity.notFound().build();
    }
}

测试日志:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /API/login
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"49"]
             Body = {"email":"[email protected]","password":"password"}
    Session Attrs = {}

Handler:
             Type = listify.controllers.APIController
           Method = listify.controllers.APIController#login(HttpSession, Map)

这似乎很奇怪,因为控制器应该接受 application/json mediaType,而不是返回该错误。

此外,如果我从 javascript 发送 ajax 请求,它可以正常工作。

JS代码:

response = await fetch(URL_PREFIX + "/listify/API/login", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({"email" : email, "password" : password}),
});

我不知道我做错了什么,我希望测试成功,因为该方法应该返回状态代码200,或者至少接受请求并打印“here”。

提前致谢。

spring spring-mvc testing http-status-code-415
1个回答
0
投票

尝试通过从

APIController
 中删除 
@SpringBootTest

来运行测试
@SpringBootTest
@AutoConfigureMockMvc
class APIControllerTest {

    @MockBean
    private ListifyService listifyService;

    @Autowired
    private MockMvc mvc;

    @Test
    void loginTest() throws Exception {
        when(listifyService.login(anyString(), anyString())).thenReturn("aless");

        String url = "/API/login";

        String requestJson = "{" +
                "\"email\":\"[email protected]\"," +
                "\"password\":\"password\"" +
                "}";

        mvc.perform(post(url)
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .characterEncoding("UTF-8") //if i remove this instruction, the body won't be send (empty body in test log)
                    .content(requestJson))
                    .andDo(print())
                    .andExpect(status().isOk());
    }


也不要手动序列化请求正文,而是尝试使用

ObjectMapper

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.