easymock单元测试实例二
来源:互联网 发布:大数据安全与隐私保护 编辑:程序博客网 时间:2024/06/05 04:21
public class SampleServlet extends HttpServlet { public boolean isAuthenticated(HttpServletRequest request){ HttpSession session=request.getSession(false); if(session==null){ return false; } String authenticationAttribute = (String) session.getAttribute("authenticated"); return Boolean.valueOf(authenticationAttribute).booleanValue(); }}
本实例的测试目标是SampleServlet的isAuthenticated方法。为了测试该方法,可以有两种解决方案:
1.使用mock objects 来测试。
2.在容器中测试,即 in-container testing
首先使用第一种方法,使用mock objects来测试:
package easymock;import org.junit.After;import org.junit.Before;import org.junit.Test;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import static junit.framework.Assert.assertFalse;import static junit.framework.Assert.assertTrue;import static org.easymock.EasyMock.*;/** * Created by yameng on 14-1-12. */public class EasyMockSampleServletTest { private SampleServlet sampleServlet; private HttpServletRequest mockHttpServletRequest; private HttpSession mockHttpSession; @Before public void setUp(){ sampleServlet=new SampleServlet(); mockHttpServletRequest=createStrictMock(HttpServletRequest.class); mockHttpSession = createStrictMock(HttpSession.class); } @Test public void testIsAuthenticatedAuthenticated() { expect(mockHttpServletRequest.getSession(eq(false))).andReturn(mockHttpSession); expect(mockHttpSession.getAttribute(eq("authenticated"))).andReturn("true"); replay(mockHttpServletRequest); replay(mockHttpSession); assertTrue(sampleServlet.isAuthenticated(mockHttpServletRequest)); } @Test public void testIsAuthenticatedNotAuthenticated() { expect(mockHttpSession.getAttribute(eq("authenticated"))).andReturn("false"); replay(mockHttpSession); expect(mockHttpServletRequest.getSession(eq(false))).andReturn(mockHttpSession); replay(mockHttpServletRequest); assertFalse(sampleServlet.isAuthenticated(mockHttpServletRequest)); } @Test public void testIsAuthenticatedNoSession() { expect(mockHttpServletRequest.getSession(eq(false))).andReturn(null); replay(mockHttpServletRequest); replay(mockHttpSession); assertFalse(sampleServlet.isAuthenticated(mockHttpServletRequest)); } @After public void tearDown(){ verify(mockHttpServletRequest); verify(mockHttpSession); }}
0 0
- easymock单元测试实例二
- EasyMock 单元测试
- EasyMock 单元测试
- EasyMock 单元测试过程中模拟相关类的实例
- 移:使用easymock单元测试
- 使用EasyMock进行单元测试
- 使用EasyMock辅助单元测试
- EasyMock构建单元测试
- easymock,辅助单元测试
- 用EasyMock做单元测试
- 使用easymock做单元测试
- 在单元测试中使用EasyMock
- 在单元测试中使用EasyMock
- 在单元测试中使用EasyMock
- 在单元测试中使用EasyMock
- 在单元测试中使用EasyMock
- 在单元测试中使用EasyMock
- 在单元测试中使用EasyMock
- 在Ubuntu上使用vsftpd搭建FTP服务器
- secureCRT给我加了个0D
- ZOJ-2240
- VS2005 添加右键快捷菜单
- HDU 1064(水题)
- easymock单元测试实例二
- c# 读xml文件
- WinCE驱动编写小结
- wxListCtrl的基本用法
- C与C++的兼容问题——extern "C"的用法解析
- leetcode_Evaluate Reverse Polish Notation
- Platform Builder实践之两个要点(by fllsoft)
- 如何修改tomcat7的端口和用户名密码?
- Platform Builder实践之文件系统(by fllsoft)