且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-17 11:28:40

基于注解的 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.