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 when the web app runs on servlet container (or when I debug the code), no data returns when I invoke it from a test class based on JUnit 5
with Mockito
.
Here is my configuration:
@ContextConfiguration(classes = {WebAppInitializer.class, AppConfig.class, WebConfig.class})
@Transactional
@WebAppConfiguration
public class TestMainController {
@InjectMocks
private MainController mainController;
private MockMvc mockMvc;
@BeforeEach
public void init() {
mockMvc = MockMvcBuilders.standaloneSetup(this.mainController).build();
}
@Test
public void testLoadData() throws Exception {
MvcResult mvcResult = mockMvc
.perform(MockMvcRequestBuilders.get("/loadData.ajax"))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
Assertions.assertNotNull(mvcResult.getResponse().getContentAsString(), "response should not be null");
}
}
The test fails due to java.lang.NullPointerException
as the this.mainController
is null
.
Environment Details:
Spring version: 5.0.3
JUnit version: 5.0.3
mockito version: 1.9.5
hamcrest version: 1.3
json-path-assert version: 2.2.0
Edit: Here is the loadData
method of MainController
:
@RequestMapping(value = "/loadData.ajax", method = RequestMethod.GET)
public String loadData(HttpServletRequest request, HttpServletResponse response) {
List list = mainService.loadData(); // starts a transaction and invokes the loadData method of mainDAO repository which basically loads data from the database
return JSONArray.fromObject(list).toString();
}