网上有很多使用EasyMock的expect()来设置模拟对象request的参数的,我们就不去做重复工作了,下面给大家讲一下网上没有的案例,是我们项目中的真实案例:
本文也是是对《让导出Excel变的easy一些!》一文的测试,导出Excel具体怎么导出请看《让导出Excel变的easy一些!》,本节重点是对EasyMock的补充,使用EasyMock模拟response.getOutputStream()。
代码如下:
package com.jhaso.action;
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List;
import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.easymock.EasyMock;
|
public class AgeContActionTest extends TestCase { /** * * @throws IOException * @throws ServletException */ public void testToReportExcel() throws IOException, ServletException { /** * 1)创建HttpServletRequest模拟对象。 2)设置HttpServletRequest对象的模拟属性和方法 3)设置回访模式 * 4)创建LoginServlet实例,并使用模拟的request执行测试 5)调用verify()执行验证 */ // 获取Mock對象 HttpServletRequest request = EasyMock .createMock(HttpServletRequest.class); HttpServletResponse response = EasyMock .createMock(HttpServletResponse.class); List<String> c = new ArrayList<String>(); c.add("Content-Disposition"); c.add("attachment;fileName=合同报表.xls"); // 最重要--模拟request.getParameter()的值 EasyMock.expect(response.getHeaderNames()).andReturn(c); EasyMock.expect(response.getOutputStream()).andReturn( new ServletOutputStream() { public void write(int b) throws IOException { ByteArrayOutputStream OutputStreamBuffer = new ByteArrayOutputStream(); OutputStreamBuffer.write(b); } //重写write方法是必不可少! public void write(byte[] data, int offset, int length) { ByteArrayOutputStream OutputStreamBuffer = new ByteArrayOutputStream(); OutputStreamBuffer.write(data, offset, length); } }); // 設置回访模式 EasyMock.replay(request); EasyMock.replay(response); // 进行测试 AgeContAction aca = new AgeContAction(); aca.toReportExcel(request, response);
|
// 在调用的模拟对象前,一定要执行verify操作 EasyMock.verify(request); //注意:response这个可以不verify,如果verify本次测试将显示红条,但不影响导出的。 //EasyMock.verify(response); } }
|
【注意】:
EasyMock.expect(response.getOutputStream()).andReturn(
new ServletOutputStream() {
public void write(int b) throws IOException {
ByteArrayOutputStream OutputStreamBuffer = new ByteArrayOutputStream();
OutputStreamBuffer.write(b);
}
//重写write方法是必不可少!
public void write(byte[] data, int offset, int length) {
ByteArrayOutputStream OutputStreamBuffer = new ByteArrayOutputStream();
OutputStreamBuffer.write(data, offset, length);
}
});
这段代码是你能否测试成功的关键!必须对自己去重写writer方法!