gpt4 book ai didi

java - 如何使用 JUnit、Resteasy 和 Jetty 测试 JAX-RS 应用程序

转载 作者:行者123 更新时间:2023-12-02 01:22:18 26 4
gpt4 key购买 nike

我正在尝试以测试驱动的方式编写基于 JAX-RS 的 Restful 应用程序。我不想使用 spring-boot,只想使用 JavaEE 规范及其(主要基于 Wildfly)实现。

我编写了 JAX-RS 应用程序的一个非常小的实现,并试图对它按照我期望的方式失败的部分进行自动化测试(因为资源返回 nullcreate 调用上。

我想创建一个设置,在其中我的测试启动一个基本容器 Jetty,该容器使用 Resteasy 作为 JAX-RS 实现为我的应用程序提供服务。然后我想对我的应用程序的资源运行一些测试,之后我想拆除服务器。

到目前为止,一切都很好,没什么特别的。但是,我无法让它工作。我尝试了多种方法,但 Resteasy 似乎不会自动获取我的 JAX-RS 注释的应用程序和资源,尽管它应该能够这样做。

如果我明确告诉 Resteasy 我的应用程序是什么,这似乎至少有效,但当然,我的资源不会被获取。

我的应用程序类:

@ApplicationPath("/service")
public class AssurancetourixRestApplication extends Application
{
private static final Logger log = LoggerFactory.getLogger(AssurancetourixRestApplication.class);

public AssurancetourixRestApplication()
{
log.info("Application created");
}

@Override
public Set<Class< ? >> getClasses()
{
log.info("getClasses called");
return super.getClasses();
}

@Override
public Set<Object> getSingletons()
{
log.info("getSingletons called");
return super.getSingletons();
}
}

我的资源界面:

@Path("insurance")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public interface InsuranceResource
{
@GET
public Response getAll();

@POST
public Response create(Insurance insurance);
}

资源的实现:

public class InsuranceResourceImpl implements InsuranceResource
{
private static final Logger log = LoggerFactory.getLogger(InsuranceResourceImpl.class);

public InsuranceResourceImpl()
{
log.info("resource created");
}

@Override
public Response create(Insurance insurance)
{
log.info("create called");
return null;
}

@Override
public Response getAll()
{
log.info("getAll called");
return null;
}
}

Web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>assurancetourix-rest</display-name>
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>nl.crashdata.assurancetourix</groupId>
<artifactId>assurancetourix</artifactId>
<version>0.1-SNAPSHOT</version>
</parent>

<artifactId>assurancetourix-rest</artifactId>
<packaging>war</packaging>

<name>Assurancetourix rest services</name>

<dependencies>
<dependency>
<groupId>org.jboss.spec.javax.ws.rs</groupId>
<artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.xml.bind</groupId>
<artifactId>jboss-jaxb-api_2.3_spec</artifactId>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-servlet-initializer</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

依赖关系在父 pom 中管理。 Resteasy是版本3.8.1.Final,jetty是版本9.4.19.v20190610

测试类

@TestInstance(Lifecycle.PER_CLASS)
public class InsuranceResourceTest
{
private ResteasyClient resteasyClient = new ResteasyClientBuilder().build();

private Server server;

@Test
public void createInsurance()
{
Insurance insurance = new Insurance();
insurance.setName("Test insurance");
insurance.setPolicyNumber(123456789L);

Response response = post(insurance);

assertEquals(Status.CREATED, response.getStatusInfo());
}

private Response post(Insurance insurance)
{
return resteasyClient.target(server.getURI())
.proxy(InsuranceResource.class)
.path("/service")
.create(insurance);
}

@BeforeAll
protected void setUp()
{
this.server = new Server(0);

ServletContextHandler context =
new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setBaseResource(getWebAppRoot());

ServletHolder holder = new ServletHolder("default", HttpServlet30Dispatcher.class);
context.addServlet(holder, "/*");
server.setHandler(context);

try
{
server.start();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}

@AfterAll
protected void tearDown()
{
try
{
server.stop();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}

protected Resource getWebAppRoot()
{
try
{
return Resource
.newResource(new File(new File(".").getAbsolutePath() + "/src/main/webapp"));
}
catch (Exception e)
{
throw new RuntimeException();
}
}

我希望在日志中看到 NPE 以及我添加的调试日志语句,但我看到的只是:

19:06:49.157 [qtp707635461-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - RESTEASY002305: Failed executing POST /service/insurance javax.ws.rs.NotFoundException: RESTEASY003210: Could not find resource for full path: http://127.0.1.1:34977/service/insurance

值得注意的是,我没有看到我的类中的日志语句。

通过 TRACE 上的 Resteasy 日志记录,我没有得到任何包含我的应用程序或资源名称的有用信息,但我确实得到了:

19:06:49.150 [qtp707635461-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - RESTEASY002315: PathInfo: /service/insurance 19:06:49.157 [qtp707635461-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - RESTEASY002305: Failed executing POST /service/insurance javax.ws.rs.NotFoundException: RESTEASY003210: Could not find resource for full path: http://127.0.1.1:34977/service/insurance at org.jboss.resteasy.core.registry.ClassNode.match(ClassNode.java:61) ~[resteasy-jaxrs-3.8.1.Final.jar:3.8.1.Final] at SNIP 19:06:49.176 [qtp707635461-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - MessageBodyWriter: org.jboss.resteasy.spi.ResteasyProviderFactory$SortedKey 19:06:49.176 [qtp707635461-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - MessageBodyWriter: org.jboss.resteasy.plugins.providers.StringTextStar 19:06:49.176 [qtp707635461-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - MessageBodyWriter: org.jboss.resteasy.plugins.providers.StringTextStar 19:06:49.177 [qtp707635461-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - Interceptor Context: org.jboss.resteasy.core.interception.ServerWriterInterceptorContext, Method : proceed 19:06:49.177 [qtp707635461-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - MessageBodyWriter: org.jboss.resteasy.spi.ResteasyProviderFactory$SortedKey 19:06:49.178 [qtp707635461-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - MessageBodyWriter: org.jboss.resteasy.plugins.providers.StringTextStar

如果我将测试类的 setUp 方法更改为:

        this.server = new Server(0);

ServletContextHandler context =
new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");

// // this should not be necessary
ServletHolder holder = new ServletHolder("default", HttpServletDispatcher.class);
holder.setName("defaultservlet");
holder.setInitParameter("javax.ws.rs.Application",
"nl.crashdata.assurancetourix.rest.AssurancetourixRestApplication");
context.addServlet(holder, "/*");
server.setHandler(context);

try
{
server.start();
}
catch (Exception e)
{
throw new RuntimeException(e);
}

即,我硬编码了 jax-rs 应用程序的完整路径,该应用程序至少已构建,但资源似乎并未构建:

19:13:17.768 [qtp515520300-24] INFO nl.crashdata.assurancetourix.rest.AssurancetourixRestApplication - Application created 19:13:17.770 [qtp515520300-24] INFO org.jboss.resteasy.resteasy_jaxrs.i18n - RESTEASY002225: Deploying javax.ws.rs.core.Application: class nl.crashdata.assurancetourix.rest.AssurancetourixRestApplication 19:13:17.770 [qtp515520300-24] INFO nl.crashdata.assurancetourix.rest.AssurancetourixRestApplication - getClasses called 19:13:19.759 [qtp515520300-24] INFO nl.crashdata.assurancetourix.rest.AssurancetourixRestApplication - getSingletons called

然后就没有什么有趣的事情了,直到:

19:13:19.789 [qtp515520300-24] DEBUG org.jboss.resteasy.resteasy_jaxrs.i18n - RESTEASY002305: Failed executing POST /service/insurance javax.ws.rs.NotFoundException: RESTEASY003210: Could not find resource for full path: http://127.0.1.1:39075/service/insurance

我希望我做的是一些基本错误的事情。据我从 https://docs.jboss.org/resteasy/docs/3.8.1.Final/userguide/html_single/index.html 第 3.3.1 段中了解到,我不必对应用程序类名或任何内容进行硬编码,它应该自动选取。

RESTEasy uses the ServletContainerInitializer integration interface in Servlet 3.0 containers to initialize an application, automatically scanning for resources and providers. To enable automatic scanning, you must also include the resteasy-servlet-initializer artifact in your WAR file as well

希望我遗漏了一些非常容易修复的东西,并希望有人可以告诉我那是什么。 :D

最佳答案

如果你不需要使用jetty,那么resteasy提供了MockDispatcherFactory,这使得Rest-Tests的编写变得非常容易。

看看:Example of Resourcetest using restassured inherently using MockDispatcherFactoryTest by using MockDispatcherFactory directly

关于java - 如何使用 JUnit、Resteasy 和 Jetty 测试 JAX-RS 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57614397/

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