I am trying to create a test for my controller. Here’s what I have similar. Just name changes. I am using Mockito and Spring MVC. The test configuration files have the autowired beans in them mocked via mock factory. I get a null pointer…
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
...
})
public class MyReportControllerTest {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockHttpSession session;
private HandlerAdapter handlerAdapter;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private MyService myService;
@Autowired
private RequestMappingHandlerMapping rmhm;
@Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
session = new MockHttpSession();
handlerAdapter = applicationContext
.getBean(RequestMappingHandlerAdapter.class);
request.setSession(session);
request.addHeader("authToken", "aa");
Mockito.when(
myService.getMyInfo(YEAR))
.thenReturn(getMyInfoList());
}
@Test
public void testGetMyInfo(){
request.setRequestURI("/getMyInfo/" + 2011);
request.setMethod("GET");
try {
if( handlerAdapter == null){
System.out.println("Handler Adapter is null!");
}
if( request == null){
System.out.println("Request is null!");
}
if( response == null){
System.out.println("Response is null!");
}
if( rmhm.getHandler(request) == null){
System.out.println("rmhm.getHandler(request) is null!");
}
//the above returns null
System.out.println("RMHM: " + rmhm.toString());
System.out.println("RMHM Default Handler: " + rmhm.getDefaultHandler());
handlerAdapter.handle(request, response,
rmhm.getHandler(request)
.getHandler());//null pointer exception here <---
...
} catch (Exception e) {
e.printStackTrace();
fail("getMyReport failed. Exception");
}
}
public List<MyInfo> getMyInfoList(){...}
I have done a thorough debugging and found that the Handler remains null for my mock request. What am I missing that it doesn’t get turned into a handler, or even goes to the default handler?
You’ve got a number of problems here.
Firstly, are you attempting to unit test your Controller, or integration test it?
It certainly looks more like an integration test; you’ve got Spring
@Autowiredannotations and a@ContextConfiguration.But if that’s the case, why are you attempting to define mock behaviour on
myService? That’s never going to work – Spring will inject a “real” instance and Mockito has no hope of working its magic on that.Related; you are missing any kind of mock initialization call which would be required if you want that to work.
Finally, why are you doing all of this wiring up (HandlerMappings, HandlerAdapters etc) when judging by the name of your test, all you really want to do is test your
MyReportController? Can you not simply call the necessary “endpoint” method with a mock request, response etc as required?