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.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With