EasyMock采用“记录-----回放”的工作模式,基本使用步骤:
- 创建Mock对象的控制对象Control。
- 从控制对象中获取所需要的Mock对象。
- 记录测试方法中所使用到的方法和返回值。
- 设置Control对象到“回放”模式。
- 进行测试。
- 在测试完毕后,确认Mock对象已经执行了刚才定义的所有操作。
找了个例子,这个例子的主要功能是模拟HttpServlet对servlet进行测试。
package com.servlet.test;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
public class LoginServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 6648223615334008738L;
protected void doGet(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException,
IOException
{
super.doGet(httpServletRequest, httpServletResponse);
}
public void doPost(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException,
IOException
{
// super.doPost(httpServletRequest, httpServletResponse);
String username = httpServletRequest.getParameter("username");
String password = httpServletRequest.getParameter("password");
System.out.println(">>>>> " + username + " " + password);
}
}
mock测试:
package com.servlet.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.verify;
import static org.easymock.EasyMock.replay;
import junit.framework.TestCase;
public class TestMockUnit extends TestCase
{
public void testLoginFailed() throws IOException, ServletException
{
// 1.获取Mock对象。
// 因为在doGet()和doPost()用到了HttpServletRequest
HttpServletRequest request = createMock(HttpServletRequest.class);
// 2.对象,需要对其模拟
// 模拟httpServletRequest.getParameter("username");
expect(request.getParameter("username")).andReturn("12345");
// 3.得到的值。在模拟测试中,模拟对象是不执行任何业务操作的,需要模拟出来
expect(request.getParameter("password")).andReturn("ABCDEF");
replay(request);
LoginServlet servlet = new LoginServlet();
try
{
servlet.doPost(request, null);
// 4.在调用用的模拟对象前,一定要执行verify操作
verify(request);
}
catch (ServletException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
总结:上面只是让大家明白easymock的基本主要的api和功能还需要查看它的api,easymock的功能实在太多,
如果您需要在单元测试中构建 Mock 对象来模拟协同模块或一些复杂对象,EasyMock 是一个可以选用的优秀框架。
EasyMock 提供了简便的方法创建 Mock 对象:通过定义 Mock 对象的预期行为和输出,你可以设定该 Mock 对象在实
际测试中被调用方法的返回值、异常抛出和被调用次数。通过创建一个可以替代现有对象的 Mock 对象,EasyMock 使得
开发人员在测试时无需编写自定义的 Mock 对象,从而避免了额外的编码工作和因此引入错误的机会。