我想爲我的控制器創建一個測試。這是我有類似的。只是更名。我正在使用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