我正在尝试为我的控制器创建一个测试。这是我有类似的东西。只是名称更改。我正在使用 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(){...}
我进行了彻底的调试,发现 Handler 对于我的模拟请求仍然为空。我错过了什么,它没有变成处理程序,甚至没有转到默认处理程序?