如何对Spring MVC带注释的控制器进行单元测试?

时间:2011-04-25 01:07:46

标签: java spring junit annotations

我正在关注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,有人可以解释一下如何对最后一个控制器进行单元测试吗?

3 个答案:

答案 0 :(得分:25)

基于注释的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());
       ...
   }
}

这种方法有问题吗?

对于更高级的集成测试,reference in Spring documentation有一个org.springframework.mock.web

答案 1 :(得分:21)

使用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可以解决问题。

答案 2 :(得分:1)

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