【项目地址】
https://github.com/easymock/easymock
【简介】
EasyMock is a Java library that provides an easy way to use Mock Objects in unit testing.
You can find the website and user documentation at http://easymock.org.
【我的目的】
测试一个以HttpServletRequest对象为参数的方法,测试过程中还发现牵涉到HttpSession
【代码】
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
......
// Step 1 - 创建要mock的对象
HttpServletRequest req = createMock(HttpServletRequest.class);
HttpSession session = createMock(HttpSession.class);
// 对于将被调用的方法,使用expect指定返回值
expect(session.getAttribute("USER_INFO")).andReturn(null).times(1, 2);
expect(req.getSession()).andReturn(session).times(1, 2);
expect(req.getHeader("iv-user")).andReturn("testUser1").times(1, 2);
Vector<String> groups = new Vector<String>();
groups.add("group1");
groups.add("group2");
groups.add("staff in (p)22");
Enumeration<String> emun = groups.elements();
expect(req.getHeaders("iv-groups")).andReturn(emun).times(1, 2);
//如果mock对象的方法返回void,不能使用expect方法,而应该使用如下模式:先调用void方法,再调用expectLastCall()
session.setAttribute("USER_INFO", null);
EasyMock.expectLastCall();
// 准备模拟对象data
replay(session);
replay(req);
......
try {
//Mock对象完毕,开始测试....
List userInfo = BizUtils.getUserInfo(req);
assertTrue(userInfo!=null && userInfo.size()==2);
【简单总结】
由于时间关系没有做太多研究,要注意的地方就是:
- 本来只需要模拟HttpServletRequest,但被测试方法在执行过程中调用了request.getSession(),本来可以使用expect来处理该方法,但session我也是没办法自己随意创建的,也不能直接置为null,所以干脆也mock一个HttpSession;
- 对于返回为void的方法,处理方式较为特别