如何对Spring MVC带注释的控制器进行unit testing?

我正在关注Spring 2.5教程并尝试将代码/设置更新到Spring 3.0。

Spring 2.5中,我有HelloController (供参考):

public class HelloController implements Controller { protected final Log logger = LogFactory.getLog(getClass()); public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("Returning hello view"); return new ModelAndView("hello.jsp"); } } 

以及HelloController的JUnit测试(供参考):

 public class HelloControllerTests extends TestCase { public void testHandleRequestView() throws Exception{ HelloController controller = new HelloController(); ModelAndView modelAndView = controller.handleRequest(null, null); assertEquals("hello", modelAndView.getViewName()); } } 

但现在我将控制器更新到Spring 3.0 ,它现在使用注释(我还添加了一条消息 ):

 @Controller public class HelloController { protected final Log logger = LogFactory.getLog(getClass()); @RequestMapping("/hello") public ModelAndView handleRequest() { logger.info("Returning hello view"); return new ModelAndView("hello", "message", "THIS IS A MESSAGE"); } } 

知道我正在使用JUnit 4.9,有人可以解释一下如何对最后一个控制器进行unit testing吗?

基于注释的Spring MVC的一个优点是它们可以以简单的方式进行测试,如下所示:

 import org.junit.Test; import org.junit.Assert; import org.springframework.web.servlet.ModelAndView; public class HelloControllerTest { @Test public void testHelloController() { HelloController c= new HelloController(); ModelAndView mav= c.handleRequest(); Assert.assertEquals("hello", mav.getViewName()); ... } } 

这种方法有问题吗?

对于更高级的集成测试, Spring文档中引用了org.springframework.mock.web 。

使用mvc:annotation-driven,您必须有两个步骤:首先使用HandlerMapping将请求解析为处理程序,然后您可以通过HandlerAdapter使用该处理程序执行该方法。 就像是:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("yourContext.xml") public class ControllerTest { @Autowired private RequestMappingHandlerAdapter handlerAdapter; @Autowired private RequestMappingHandlerMapping handlerMapping; @Test public void testController() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); // request init here MockHttpServletResponse response = new MockHttpServletResponse(); Object handler = handlerMapping.getHandler(request).getHandler(); ModelAndView modelAndView = handlerAdapter.handle(request, response, handler); // modelAndView and/or response asserts here } } 

这适用于Spring 3.1,但我想每个版本都必须存在一些变体。 看看Spring 3.0代码,我会说DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter可以解决这个问题。

您还可以查看其他独立于Spring的Web测试框架,如HtmlUnit或Selenium 。 除了Sasha描述的内容之外,你不会仅仅使用JUnit找到更强大的策略,除非你应该断言模型。