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