java - 如何对 Spring MVC 注释 Controller 进行单元测试?

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

但现在我将 Controller 更新为 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,有人能解释一下如何对最后一个 Controller 进行单元测试吗?

最佳答案

基于注解的 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 documentationorg.springframework.mock.web .

关于java - 如何对 Spring MVC 注释 Controller 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774349/

相关文章:

java - 如何将整数转换为 base64 (0-9A-Za-z)

java - Android读取xml错误

java - 禁用滚动到焦点单元格

spring - 如何将系统属性传递给 Gradle 任务

java - 测试反射 newInstance 异常

java - @SpringApplicationConfiguration 和@ContextConfiguration 的区别

java - 如何使用 Rest API 和 Java 在 Egnyte 中上传 pdf 文件

java - 如何在 spring oauth2 security 中登录 successHandler 后立即获取访问 token ?

java - 在 Angular 2 中设置授权 header

java - 为网络相关类编写单元测试