I try to test a method named as loadData
defined in MainController
which returns result as a string. Despite that this method actually returns data
You can call controller method directly, just like we do for service method, but this is not recommended. Using MockMvc, you check for header and request param mapping are proper. Plus, you also check for end point mapping is correct. Plus the Request METHOD is also correct. All these you cannot test if you test your code by directly calling the controller method.
One thing you can try is, instead of creating new object inside the standalone context, use the Mock. i.e
mockMvc = MockMvcBuilders.standaloneSetup(this. mainController).build();
And while calling, do this
MvcResult mvcResult = mockMvc
.perform(MockMvcRequestBuilders.get("/loadData.ajax"))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
Assert , what you would like to
Assert.assertEquals("response does not match", mvcResult.getResponse().getContentAsString(),
"some expected response");
You are getting null or 400 or 404 http status ?
If you are getting 400, then please check the header and req. param if any are proper. If you are getting 404 then please check the URL path. /loadData.ajax , assuming this is your request mapping path in controller method.