Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.AssertionError: Content type not set even after setting content type as json/application

This question has been asked before and I have tried their solution but that doesn't work for me, I am using MockMvc to unit test content type of my rest call. I am getting this exception:

java.lang.AssertionError: Content type not set

While I'm setting it in my search method using produces attribute.

This is the method where I am initializing the mocks:

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    ReflectionTestUtils.setField(restController, "luceneSearchEnabled", true);
    mockMvc = standaloneSetup(restController).build();
}

This is my test method:

@Test
public void pmmSearchContentTypeTest() throws Exception { 
    mockMvc
          .perform(get("/api/v1/pmm").contentType(MediaType.APPLICATION_JSON))
          .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_VALUE)
          .andReturn();
}

This is my search method where I am setting content type:

@RequestMapping(value = "/api/" + REST_API_VERSION + "/" + ONE_INTERFACE, method = RequestMethod.GET, produces ={MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public String pmmSearch() { ... }

I don't know what is wrong here.

like image 875
jack Avatar asked May 25 '16 22:05

jack


2 Answers

I faced the same error and found that , the mock service for this controller method returns null. change mock service method to return values for any() input and test this to get rid of this error.

when(service.method(any())).thenReturn(someElement);

someElement was null earlier causing this error case

like image 59
Vimalkumar Natarajan Avatar answered Nov 12 '22 18:11

Vimalkumar Natarajan


Figured it out myself

Instead of using the mock object of retcontroller here

mockMvc = standaloneSetup(restController).build();

I had to use a real object

mockMvc = standaloneSetup(new RestController()).build();

and in order to avoid spring validation error I had to use complete path here

mockMvc
.perform(get("/api/v1/pmm/search{}").contentType(MediaType.APPLICATION_JSON))
like image 45
jack Avatar answered Nov 12 '22 18:11

jack