gpt4 book ai didi

java - Jersey JUnit 测试 : @WebListener ServletContextListener not invoked

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:09:26 26 4
gpt4 key购买 nike

我在 Jersey 中创建了这个测试(来自 docs ),它工作正常,但有一个问题:未调用 @WebListener ServletContextListener

我需要测试的资源类依赖于 ServletContextListener 在 ServletContext 上设置的属性。

我能否确保它被调用,或者我能否以其他方式操纵 ServletContext?

public class SimpleTest extends JerseyTest {

@WebListener
public static class AppContextListener implements ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("Context initialized");
}

@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("Context destroyed");
}
}

@Path("hello")
public static class HelloResource {
@GET
public String getHello() {
return "Hello World!";
}
}

@Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}

@Test
public void test() {
final String hello = target("hello").request().get(String.class);
assertEquals("Hello World!", hello);
}
}

我添加了这些依赖项以使其工作:

<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<version>2.18</version>
</dependency>

<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.18</version>
</dependency>

最佳答案

JerseyTest 需要设置为在 Servlet 环境中运行,如 mentioned here .以下是好的部分:

@Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}

@Override
protected DeploymentContext configureDeployment() {
ResourceConfig config = new ResourceConfig(SessionResource.class);
return ServletDeploymentContext.forServlet(new ServletContainer(config))
.addListener(AppContextListener.class)
.build();
}

查看 API

关于java - Jersey JUnit 测试 : @WebListener ServletContextListener not invoked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30896911/

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