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

问题描述:

我正在关注 Spring 2.5 教程,同时尝试将代码/设置更新到 Spring 3.0.

I am following a Spring 2.5 tutorial and trying, at the same time, updating the code/setup to Spring 3.0.

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

In Spring 2.5 I had the HelloController (for reference):

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 测试(供参考):

And a JUnit test for the HelloController (for reference):

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,并且它现在使用了注释(我还添加了一个消息):

But now I updated the controller to Spring 3.0, and it now uses annotations (I also added a message):

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

Knowing that I am using JUnit 4.9, can some one explain me how to unit test this last controller?

基于注解的 Spring MVC 的一个优点是它们可以以一种直接的方式进行测试,如下所示:

One advantage of annotation-based Spring MVC is that they can be tested in a straightforward manner, like so:

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());
       ...
   }
}

这种方法有什么问题吗?

Is there any problem with this approach?

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

For more advanced integration testing, there is a reference in Spring documentation to the org.springframework.mock.web.