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

2022-01-13 00:00:00 annotations spring java junit

我正在关注 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.

相关文章