我有一个实现 ServletContextListener
的对象,根据 Java EE servlet 规范,servlet 容器在部署/启动时通过其 contextInitialized(ServletContext)
调用> 方法。
我正在尝试编写一个单元测试来模拟启动和部署我的 ServletContextListener
的 servlet 容器(以便我可以确定应用程序是否正确初始化)。
这是否可能,如果可能,如何实现?它是特定于容器的吗?如果是这样,我正在使用 OGS。寻找看起来像这样的东西的代码:
@Test
public void shouldBootstrapAppAtDeployTime() {
// Given
GlassFishContainer container = new GlassFishContainer(); // ha!
MyApp app = mock(MyApp.class); // MyApp implements ServletContextListener
// When - deploy app to container
// Causes app.contextInitialized(ServletContext) to be called
container.deploy(app);
// Then - verify the method was called with any ServletContext
mock.verify(app.contextInitialized(Matchers.any());
}
这是草率的伪代码,为了演示目的(只是为了表达我的意图)散布了一些实现不佳的 Mockito。提前致谢!
最佳答案
也许你可以用 Arquillian 解决这个问题:http://arquillian.org/features/
来自网页:
Arquillian brings your test to the runtime, giving you access to container resources, meaningful feedback and insight about how the code really works.
关于java - 如何在单元测试中模拟/ stub Java 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10837839/