2016-11-09 89 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() 方法检查结果。