JMOCK


在web项目中测试servlet比较麻烦,像servletRequest,servletResponse等对象就很难构建(它们都是interface),假如你有一个登录服务,在服务中需要把某些值设入session:

public class UserLoginService {
    private HttpServletRequest req;
    private String returnPage;
   
    public UserLoginService(HttpServletRequest req, String returnPage) {
        this.req = req;
        this.returnPage = returnPage;
    }

    public String login(String id, String pwd) {

       req.getSession().setAttribute("isLogin",true);

}

}

在单元测试中,就需要构建request对象,一种方法就是使用httpClient来创建测试request对象,另外一种就是使用Mock Objects,创建模拟request的对象。模拟对象经常使用的场合包括:

1、很难构建的对象(主要是接口对象)

2、非常消耗资源(资源主要指时间)

JMock就是其中的一种Mock Object Library,比较常用的还有easyMock

下面看一下我的单元测试代码:

public class UserLoginServiceTest extends MockObjectTestCase {
   
    private DefaultResultStub returnADefaultValue = new DefaultResultStub(); 
   
    public void testLogin() {
        Mock reqMock = new Mock(HttpServletRequest.class);
        UserLoginService service = new UserLoginService((HttpServletRequest)reqMock.proxy(), "index.jsp");
        reqMock.stubs().method("getSession").will(returnADefaultValue);
        assertEquals("index.jsp", service.login("admin", "*"));
    }
}

先创建一个HttpServletRequest的Mock对象,然后调用Mock对象的Proxy方法产生一个HttpServletRequest实例,最后,你需要创建一个getSession方法的Matcher(因为我调用了request对象的getSession方法)。

这只是JMock的一种简单用法,它的功能很强,不但能模拟interface,而且通过CGLIB,还可以测试concrete class。如果你对JMock感兴趣,可以访问它的网站。

posted on 2004-12-14 22:31  笨笨  阅读(1840)  评论(0编辑  收藏  举报

导航