2016-11-09 95 views
1

我在Spring Web模型 - 視圖 - 控制器(MVC)框架應用程序 中使用Mockito(在MIT許可證下發布的Java開源測試框架)進行junit測試在控制器方法:Mockito:檢查響應頭和狀態

@RequestMapping(value = { "/devices" } , method = { RequestMethod.GET, RequestMethod.POST}) 
    public void initGetForm(@ModelAttribute("searchForm") final SearchForm searchForm, 
          HttpServletRequest request, 
          HttpServletResponse response, 
          Locale locale) throws Exception { 

     String newUrl = request.getContextPath() + "/devices/" + locale; 

     if (locale !=null && isValid(locale)) { 
      newUrl = request.getContextPath() + "/devices/" + DEFAULT_LOCALE;   
     } 

     redirectPermanently (response, newUrl);  

    } 




    protected void redirectPermanently (HttpServletResponse response, String to) { 

     response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); 
     response.setHeader("Location", to); 
     response.setHeader("Connection", "close"); 
     } 

,這是我的測試類:

@Test 
    public void testInitGetForm() throws Exception { 

     controller.initGetForm(emptySearchForm(), request, response, null); 

    } 

@Before 
public void setUpTest() { 
    request = new MockHttpServletRequest(); 
    response = new MockHttpServletResponse(); 
} 

是否有可能檢查響應的頭和狀態?????

+0

此測試不使用Mockito。 –

回答

1

您可以使用spring-test模塊中的MockHttpServletResponseMockHttpServletRequest的實例。 將它們傳遞給您的控制器,然後使用MockHttpServletResponse.getStatus()MockHttpServletResponse.containsHeader() 方法檢查結果。