gpt4 book ai didi

java - Junit 和 EasyMock Servlet 测试

转载 作者:行者123 更新时间:2023-11-30 04:27:09 25 4
gpt4 key购买 nike

我在测试 Servlet 时遇到问题。 Bouncer 是一个带有简单方法 doPost 和 init 的 Servlet,被我重写了。但是当我运行该代码时,我遇到异常

@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.MockInitationHandler.invoke(MockInitationHandler.java:32)...

如果有人知道如何解决它,我将不胜感激。

最佳答案

该错误表明 easymock 在模拟对象中遇到了方法调用 getMethod() 。逐行调试程序并添加对模拟对象的期望调用。

如果它不是模拟对象,则不必在 Expect 中添加方法调用,但模拟对象中的所有调用都应添加到您的测试方法中。

在服务中调用 getMethod() ,并且由于您正在模拟 HttpServletRequest ,因此还需要模拟 HttpServletRequest 上的所有方法调用

关于java - Junit 和 EasyMock Servlet 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15592597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com