我在测试Servlet时遇到了一个问题。Bouncer是一个Servlet,带有简单的方法doPost和init,被我重写了。但是当我运行该代码时,我得到了异常
@Before
public void Before() throws IOException, ServletException,
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, SecurityException, ClassNotFoundException {
encoder = EasyMock.createMock(Encoder.class);
EasyMock.expect(encoder.encode("password")).andReturn("asdf");
EasyMock.expect(encoder.encode("nic")).andReturn("asss");
EasyMock.expect(encoder.encode("Password")).andReturn("ass");
EasyMock.replay(encoder);
db = EasyMock.createMock(UserDataBase.class);
db.connect();
EasyMock.expect(db.isConnected()).andReturn(true);
EasyMock.expect(db.getUserByLoginAndPassword("login", "asss"))
.andReturn(null);
EasyMock.expect(db.getUserByLoginAndPassword("login", "asdf"))
.andReturn(new User("Rafal", "Machnik"));
EasyMock.expect(db.getUserByLoginAndPassword("fake", "asdf"))
.andReturn(null);
EasyMock.expect(db.getUserByLoginAndPassword("login", "ass"))
.andReturn(null);
EasyMock.replay(db);
lsf = EasyMock.createMock(LoginServiceFactory.class);
EasyMock.expect(lsf.getEncoder()).andReturn(encoder).anyTimes();
EasyMock.expect(lsf.getUserDataBase()).andReturn(db).anyTimes();
EasyMock.replay(lsf);
config = EasyMock.createMock(ServletConfig.class);
EasyMock.expect(config.getInitParameter("LoginServiceFactory"))
.andReturn("pl.to.cw4.LoginServiceFactory");
EasyMock.replay(config);
request = EasyMock.createMock(HttpServletRequest.class);
EasyMock.expect(request.getParameter("login")).andReturn("login")
.anyTimes();
EasyMock.expect(request.getParameter("password")).andReturn("password")
.anyTimes();
EasyMock.replay(request);
pageSource = new StringWriter();
response = EasyMock.createMock(HttpServletResponse.class);
EasyMock.expect(response.getWriter())
.andReturn(new PrintWriter(pageSource)).anyTimes();
EasyMock.replay(response);
bouncer = new Bouncer(lsf);
bouncer.init(config);
}
@Test
public void bouncerTest() throws ServletException, IOException {
bouncer.service(request, response);
assertNotNull(pageSource.toString());
}java.lang.AssertionError:意外的方法调用getMethod():在org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:32)...
如果有人知道如何修复它,我将不胜感激。
发布于 2013-03-24 06:08:49
该错误表明easymock在模拟对象中遇到了调用getMethod()的方法。逐行调试程序,并为模拟对象添加一个expect调用。
如果不是模拟对象,则不必在expect中添加方法调用,但应将模拟对象中的所有调用添加到测试方法中。
getMethod()是在服务中调用的,由于您模拟的是HttpServletRequest,因此还需要模拟HttpServletRequest上的所有方法调用
发布于 2013-03-24 06:08:23
service()方法根据请求调用getMethod(),以确定它是否必须调用doGet()、doPost()或其他servlet方法。因为您没有在模拟请求中存根这个对getMethod()的调用,所以EasyMock会抛出这个异常。
既然service()是您想要测试的方法,那么为什么不直接调用doPost(),而是调用它呢?
https://stackoverflow.com/questions/15592597
复制相似问题