對于Junit4,此支持包括一個名為SpringJunit4ClassRunner的自定義Junit Runner和一個用于加載相關Spring配置的自定義批注。
樣本集成測試將遵循以下原則:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/META-INF/spring/webmvc-config.xml", "contextcontrollertest.xml"})
public class ContextControllerTest {@Autowiredprivate RequestMappingHandlerAdapter handlerAdapter;@Autowiredprivate RequestMappingHandlerMapping handlerMapping;......@Testpublic void testContextController() throws Exception{MockHttpServletRequest httpRequest = new MockHttpServletRequest("POST","/contexts");httpRequest.addParameter("name", "context1");httpRequest.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE,new FlashMap());MockHttpServletResponse response = new MockHttpServletResponse();Authentication authentication = new UsernamePasswordAuthenticationToken(new CustomUserDetails(..), null);SecurityContextHolder.getContext().setAuthentication(authentication);Object handler = this.handlerMapping.getHandler(httpRequest).getHandler();ModelAndView modelAndView = handlerAdapter.handle(httpRequest, response, handler);assertThat(modelAndView.getViewName(), is("redirect:/contexts"));}
}
我已經使用MockHttpServletRequest創建對“ / contexts” uri的虛擬POST請求,并為Controller中可用的Spring Security相關細節添加了一些身份驗證細節。 正在驗證控制器返回的ModelAndView,以確保返回的視圖名稱符合預期。
執行與控制器相關的集成的更好方法是使用一個相對較新的Spring項目Spring-test-mvc ,該項目提供了一種流暢的方法來測試控制器流。 使用Spring-test-mvc,與上述相同的測試如下所示:
@Test
public void testContextController() throws Exception{Authentication authentication = new UsernamePasswordAuthenticationToken(new CustomUserDetails(..), null);SecurityContextHolder.getContext().setAuthentication(authentication);xmlConfigSetup("classpath:/META-INF/spring/webmvc-config.xml", "classpath:/org/bk/lmt/web/contextcontrollertest.xml").build().perform(post("/contexts").param("name", "context1")).andExpect(status().isOk()).andExpect(view().name("redirect:/contexts"));
}
現在,測試變得更加簡潔,無需直接處理MockHttpServletRequest和MockHttpServletResponse實例,并且讀取效果很好。
我對靜態導入的數量和此處涉及的函數調用的數量有所保留,但是與其他所有內容一樣,這只是適應這種測試方法的問題。
WEB-INF位置下的資源也可以通過以下方式與spring-test-mvc一起使用:
xmlConfigSetup("/WEB-INF/spring/webmvc-config.xml","classpath:/org/bk/lmt/web/contextcontrollertest.xml").configureWebAppRootDir("src/main/webapp", false).build().perform(post("/contexts").param("name", "context1")).andExpect(status().isOk()).andExpect(view().name("redirect:/contexts"));xmlConfigSetup("/WEB-INF/spring/webmvc-config.xml", "classpath:/org/bk/lmt/web/contextcontrollertest.xml").configureWebAppRootDir("src/main/webapp", false).build().perform(get("/contexts")).andExpect(status().isOk()).andExpect(view().name("contexts/list"));
參考: all和其他博客中的JCG合作伙伴 Biju Kunjummen提供的Spring MVC集成測試 。
翻譯自: https://www.javacodegeeks.com/2012/07/spring-mvc-integration-tests.html