2012-10-19 103 views
0

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

我已經做了徹底的調試,發現處理程序仍然爲我的模擬請求爲空。我錯過了什麼,它不會變成一個處理程序,甚至去默認處理程序?

回答

0

這裏有很多問題。

首先,您是否在嘗試單元測試您的Controller或集成測試過? 它看起來更像是一個集成測試;你有Spring @Autowired註釋和@ContextConfiguration

但是,如果是這樣的話,你爲什麼試圖在myService上定義模擬行爲?這永遠不會奏效--Spring會注入一個「真實」的實例,而Mockito沒有希望在這方面發揮它的魔力。

相關;你錯過了任何一種模擬的初始化調用,如果你想要它的話,這將是必需的。

最後,你爲什麼要做所有這些接線(HandlerMappings,HandlerAdapters等),當用你的測試名稱來判斷時,你真正想要做的就是測試你的MyReportController?你能不能簡單地根據需要用模擬請求,響應等調用必要的「端點」方法?

+0

最初的集成測試。我被給出了基本代碼,沒有任何描述測試的意圖。我意識到我不能嘲笑這項服務,所以必須進行整合,就像那樣。我只是錯過了控制器的bean沒有在測試配置文件中創建。我所做的只是增加了它,並且工作。 – user1281598

相關問題