4

I am using mockmvc for my rest services integration test. I have a post rest service, called it from postman and getted 200 but when i call it with mockmvc porform method returned 415 unsupported media type exception.

Rest method

@RequestMapping(value = "/users/test/{groupId}",
        method = RequestMethod.POST,
        produces=MediaType.APPLICATION_JSON_VALUE,
        consumes=MediaType.APPLICATION_JSON_VALUE)
private GenericResponse postTest(@PathVariable("groupId")String groupId,@RequestBody List<Contact> test, @RequestHeader("Authorization")String authorization) {
    return new GenericResponse();
}

Test Method

@Test
public void testPost() throws Exception {
    Contact contact = new Contact();
    contact.setName("contact1");
    contact.setMsisdn("901234567890");

    Contact contact2 = new Contact();
    contact2.setName("contact2");
    contact2.setMsisdn("901234567890");

    List<Contact> contactList = new ArrayList<>();
    contactList.add(contact);
    contactList.add(contact2);

    Gson gson = new Gson();
    String request = gson.toJson(contactList);

    MvcResult result = mvc.perform(
            post("/users/test/{groupId}","123")
                    .with(httpBasic(username,password))
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .accept(MediaType.APPLICATION_JSON_VALUE)
                    .content(request)
    )
            .andDo(print())
            .andExpect(status().isOk())
            .andReturn();

}

When use String instead of List in RequestBody 200 success returned. What is my mistake about collection in requestbody how can i fix it?

1 Answer 1

7

I used @EnableWebMvc annotation in controller class and worked successfully. This will activate (among others) the REST support. We need this to register the Jackson (JSON) converter in charge of serialization. There is a good explanation in https://blog.zenika.com/2013/01/15/rest-web-services-testing-with-spring-mvc/

1
  • Is there a reason why it is working now? I mean, something more than just "add this voodoo annotation here and marvel impressed", like it's always with Spring...
    – UniversE
    Commented Apr 7, 2018 at 21:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.