我想为我的控制器创建一个测试。这是我有类似的。只是更名。我正在使用Mockito和Spring MVC。测试配置文件通过模拟工厂模拟了自动布线的Bean。我得到一个空指针...我该怎么做才能解决这个问题?
@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(){...}
我已经做了彻底的调试,发现处理程序仍然为我的模拟请求为空。我错过了什么,它不会变成一个处理程序,甚至去默认处理程序?
最初的集成测试。我被给出了基本代码,没有任何描述测试的意图。我意识到我不能嘲笑这项服务,所以必须进行整合,就像那样。我只是错过了控制器的bean没有在测试配置文件中创建。我所做的只是增加了它,并且工作。 – user1281598