EasyMock辅助进行servlet测试

servelt的post处理方法:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String name = request.getParameter("username");
String password = request.getParameter("password");

System.out.println(name + " " + password);
if ("aa".equals(name) && "123".equals(password)) {
System.out.println("111");
request.getSession().setAttribute("user", new UserInfor(name,password));
out.println("ok");

} else {
out.println("error");
}
}

运用junit + EasyMock对servlet进行测试:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Test;


public class ServletDriver {


@Test
public void testJdbc() throws SQLException, IOException, ServletException {
// ResultSet mockResultSet = EasyMock.createMock(ResultSet.class);
// EasyMock.expect(mockResultSet.getString(1)).andReturn("one");
// EasyMock.replay(mockResultSet);

//应用control统一管理创建Mock对象
IMocksControl control = EasyMock.createControl();
HttpServletRequest request = control.createMock(HttpServletRequest.class);
HttpServletResponse response = control.createMock(HttpServletResponse.class);
HttpSession session = control.createMock(HttpSession.class);

//设定Mock对象的预期行为和输出
response.setContentType((String)EasyMock.anyObject());

//exceptLastCall获取上一次调用所对应的IExpectationSetters实例
EasyMock.expectLastCall().once();

EasyMock.expect(request.getParameter("username")).andReturn("aa");
EasyMock.expect(request.getParameter("password")).andReturn("123");
EasyMock.expect(response.getWriter()).andReturn(new PrintWriter(System.out,true));

//andStubReturn表示默认返回
EasyMock.expect(request.getSession()).andStubReturn(session);

/*************************************************************
* EasyMock使用参数匹配器
* EasyMock根据方法名和参数来匹配一个预期方法的调用,默认使用equals()进行
* 比较,在实际的使用过程中,比如参数是String类型的sql语句,sql语句的关键字
* 如果存在大小写的问题,那么EasyMock认为两个参数不匹配,造成Mock对象的
* 预期方法不被调用。
* 解决:使用灵活的参数匹配方式来解决这个问题。anyObject方法表示任意输入值
* 与预期值匹配。还有:aryEq,isNull,notNull,same等,具体请参考IBM技术网站
* 地址(http://www.ibm.com/developerworks/cn/opensource/os-cn-easymock/#chap3)
************************************************************/
session.setAttribute((String)EasyMock.anyObject(),EasyMock.anyObject());
EasyMock.expectLastCall().once();
//=======================以上是Mock对象的记录============================

//=======================把Mock对象切换到回放状态=========================
control.replay();

LoginServlet loginServlet = new LoginServlet();
loginServlet.doPost(request, response);


//校验行为
control.verify();

}
}

你可能感兴趣的:(单元测试,servlet,junit,EasyMock)