Spring MVC Test Framework - Unsupported Media Type

岁酱吖の 提交于 2019-12-10 17:19:17

问题


I am writing a test for controller using spring test mvc framework. I am trying to test a post request and it produces JSON. The actual code is running but test is failing.

I an getting the error Status expected 200 but getting 415 which means unsupported media type. i check all examples on net and it seems my implementation is correct. please help me out.

MyTestcase TestStringPost() is running successfully but TestJSONPost is failing.

I am using Spring 3.2

My Controller

@Controller
public class HomeController {


@RequestMapping(value = "/v1/checkstringvalue", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody void testStringPost(@RequestBody String value) {
    logger.info("Welcome home! The client locale is {}.");
}

@RequestMapping(value = "/v1/checkjsonvalue", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody String testJSONPost(@RequestBody Map<String, String> userMap) {
    System.out.println("Inside test jsonpost controller");
    logger.info("Welcome home! The client locale is {}.");
    return "Success";
 }
}

This is my Test Controller

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class HomeControllerTest {


@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

private static final String PROVIDER_A = "PROVIDER_A";

public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
        MediaType.APPLICATION_JSON.getType(),
        MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

@Configuration
public static class TestConfiguration {

    @Bean
    public HomeController simpleController() {
        return new HomeController();
    }
}

@Before
public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}

@Test
public void testStringPost() throws Exception {

    final String createJson = "hello";

    ResultActions resultActions = mockMvc.perform(post(
            "/v1/checkstringvalue").contentType(MediaType.TEXT_PLAIN)
            .content(createJson));

    resultActions.andDo(print());
    resultActions.andExpect(status().isOk());
}

@Test
public void testjsonPost() throws Exception {

    System.out.println("Inside testjsonpost");
    final String createJson = "{\"name\":\"hello\",\"email\":\"hello@example.com\"}";

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode userJson = objectMapper.createObjectNode();
    userJson.put("name", "tarun");
    userJson.put("email", "tarun@gmail.com");

    ResultActions resultActions = mockMvc
            .perform(post("/v1/checkjsonvalue")
                    .contentType(APPLICATION_JSON_UTF8)
                    .accept(APPLICATION_JSON_UTF8)
                    .content(objectMapper.writeValueAsBytes(userJson)));

    resultActions.andDo(print());
    resultActions.andExpect(status().isOk());
}
}

回答1:


Ok, so having the

perform(post("/myapi").contentType(MediaType.APPLICATION_JSON).content("{\"mykey\":\"myvalue\"}"))   

is important.

BUT also check your controller: if it is missing any of these annotations, it won't work:

@EnableWebMvc
@Controller
public class MyController {
    @RequestMapping(value="/myapi", method=RequestMethod.POST)
    public void postOnApi(@RequestBody MyWidget myWidget) {
    }
}

The @EnableWebMvc @Controller and @RequestBody are all needed (in my experimenting) to remove the 415 status code error.




回答2:


Your test code:

ResultActions resultActions = mockMvc
            .perform(post("/v1/checkjsonvalue")
                    .contentType(APPLICATION_JSON_UTF8)
                    .accept(APPLICATION_JSON_UTF8)
                    .content(objectMapper.writeValueAsBytes(userJson)));

Seems to add the contentType() header, but your source code does not have a consumes attribute in the @RequestMapping

@RequestMapping(value = "/v1/checkjsonvalue", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody String testJSONPost(@RequestBody Map<String, String> userMap) {
    System.out.println("Inside test jsonpost controller");
    logger.info("Welcome home! The client locale is {}.");
    return "Success";
 }

I think that if you take out the contentType() in your test case or add a consumes in the source code then it might work.



来源:https://stackoverflow.com/questions/23404765/spring-mvc-test-framework-unsupported-media-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!