Junit 测试 servlet--easymock

对于要在项目里对servlet进行单元测试,可以使用junit进行,而用junit测试servlet时有两种方法,一种使用httpunit + servlet测试,另一种是easymock + servlet,在这里重点介绍使用easymock方法进行的junit测试。

 

环境:eclipse 3.7 ,  junit 4 ,  easymock 3.1。

 

测试单元代码如下 : 

 

 

import static org.junit.Assert.fail;
import static org.easymock.EasyMock.*;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.joyveb.award.web.AwardResultServlet;

public class ResultServletTest {

	private AwardResultServlet servlet;
	private HttpServletRequest mockRequest;
	private HttpServletResponse mockResponse;
	
	@Before
	public void setUp(){
		servlet = new ResultServlet();
		
		mockRequest = createMock(HttpServletRequest.class);			//加载
		mockResponse = createMock(HttpServletResponse.class);
	}
	
	@After
	public void tearDown(){
		verify(mockRequest);		//验证
		verify(mockResponse);
	}
	
	
	@Test
	public void testDoPostHttpServletRequestHttpServletResponse() throws ServletException, IOException {
		
		mockRequest.getParameter("id");			//传入参数
		expectLastCall().andReturn("1");
		
		mockRequest.getParameter("name");		//传入参数
		expectLastCall().andReturn("chevy");
		
		mockRequest.getParameter("gender");		//传入参数
		expectLastCall().andReturn("男");
		
		replay(mockRequest);					//回放
		replay(mockResponse);
		
		servlet.doPost(mockRequest, mockResponse);	//调用
				
	}

}
 

 

 

 

 

servlet类就可以根据上面定义的类名,简单写个doPost方法就可以进行junit测试了。

 

 

 

 

 

 

 

 

你可能感兴趣的:(easymock)