一个Spring MVC中如何单元测试注释器? [英] How to unit test a Spring MVC annotated controller?

查看:144
本文介绍了一个Spring MVC中如何单元测试注释器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面一个Spring 2.5的教程和尝试,在同一时间,更新code /安装到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.

春季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");
    }
}

和一个JUnit测试中的的HelloController 的(供参考):

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

但现在我更新了控制器的春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?

有关更高级的集成测试,有一个<一个href=\"http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/testing.html#testcontext-framework\">reference在Spring文档到<一个href=\"http://static.springsource.org/spring/docs/3.1.0.M1/javadoc-api/org/springframework/mock/web/package-summary.html\">org.springframework.mock.web.

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

这篇关于一个Spring MVC中如何单元测试注释器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆