首先要添加djunit,junit,httpunit包
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import org.easymock.IMocksControl;
import com.ibm.dragon.service.SDCConnMgr;
import com.ibm.dragon.service.SDCConnMgrMonitorRecord;
import com.ibm.dragon.servlets.CommandServlet;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebRequest;
import com.meterware.servletunit.InvocationContext;
import com.meterware.servletunit.ServletRunner;
import com.meterware.servletunit.ServletUnitClient;
import jp.co.dgic.testing.framework.DJUnitTestCase;
import static org.easymock.EasyMock.createControl;
public class CommandServletTest extends DJUnitTestCase{
public void setUp(){
try {
super.setUp();
} catch (Exception e) {
e.printStackTrace();
}
}
public void testDoGet() throws IOException, ServletException, SQLException, NamingException{
ServletRunner sr = new ServletRunner();//创建servlet运行环境
sr.registerServlet( "CommandServlet", CommandServlet.class.getName() );//向环境中注册servlet
ServletUnitClient sc = sr.newClient();//创建访问servlet客服端
WebRequest request = new GetMethodWebRequest( "http://localhost/CommandServlet" );//发送请求
String []params = {"CLOSE_ONLINE","OPEN_ONLINE"};
request.setParameter("cmd",params);
InvocationContext ic = sc.newInvocation(request);//获得请求的上下文环境
CommandServlet is = (CommandServlet)ic.getServlet();//调用servlet非服务方法
addReturnValue("HttpServletRequest", "getParameterValues",params);
addReturnNull("DraSystem", "setOnlineServiceReady");
IMocksControl control = createControl();
Connection conn = control.createMock(Connection.class);
Hashtable v = new Hashtable();
SDCConnMgrMonitorRecord monr = new SDCConnMgrMonitorRecord(conn, "SHINEZ", "db2admin");
v.put(Integer.toString(conn.hashCode()),monr);
Enumeration em = v.elements();
addReturnValue(SDCConnMgr.class,"getMonitorRecords",em);
is.doGet(ic.getRequest(), ic.getResponse());
assertCalled("BufferedWriter", "close");
}
}
只写了测试代码,源代码不写了。