easymock单元测试实例二

本文提供了一个关于如何使用EasyMock进行单元测试的实例,详细介绍了如何通过mock objects来测试SampleServlet的isAuthenticated方法。文章包含了三个测试用例:验证已认证、未认证和无session的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值