java - 是否可以将 Spring Restdocs 与 Jersey 应用程序一起使用

标签 java spring jersey jersey-2.0 spring-restdocs

Spring Restdocs 基于 Spring MVC 测试。因此,我想弄清楚是否可以将 Spring Restdocs 与 Jersey 2.0 REST 应用程序集成。

如果是这样,您能给我指出任何相关的示例或教程吗?

最佳答案

注意:下面的更新 2:已发布用于与 Jersey 配合使用的第三方库

他们目前正在研究 restassured support它不依赖于 MVC(或任何其他服务器框架)。我想这应该在 1.1.0 中发布。我添加了feature request感谢 Jersey 测试框架的支持,但我不知道他们对此有何感想。如果您希望获得支持,可以在问题中发表评论。但我想他们会采取不需要 Jersey 测试框架支持的立场,因为您仍然可以使用 REST Assured 作为 Jersey 测试框架测试用例的客户端。但我们会看到,你永远不知道;-)


更新

因此,在发布此答案后不久,Spring REST Docs 将rest-assured 分支与master 分支合并,因此您现在可以使用spring-restdocs-restassured 工件的快照无需自己构建项目。您只需要添加 Spring 快照存储库。下面是使用 Jersey Test Framework 的完整示例。

import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.restdocs.RestDocumentation;

import com.fasterxml.jackson.databind.ObjectMapper;

import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document;
import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration;

/**
 * Stack Overflow http://stackoverflow.com/q/35068860/2587435
 * 
 * Run this like any other JUnit test. The required dependencies are listed below. You will need
 * to add the Spring Snapshot repository, also listed below.
 * 
 * Running the test should produces the following snippets in target/generated-snippets/example-put:
 * 
 * - curl-request.adoc
 * - http-request.adoc
 * - http-response.adoc
 * - path-parameters.adoc
 * - request-fields.adoc
 * - response-fields.adoc
 * 
 * <dependencies>
 *   <dependency>
 *     <groupId>org.springframework.restdocs</groupId>
 *     <artifactId>spring-restdocs-restassured</artifactId>
 *     <version>1.1.0.BUILD-SNAPSHOT</version>
 *     <scope>test</scope>
 *   </dependency>
 *   <dependency>
 *     <groupId>org.glassfish.jersey.test-framework.providers</groupId>
 *     <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
 *     <version>2.22.1</version>
 *     <scope>test</scope>
 *   </dependency>
 *   <dependency>
 *     <groupId>org.glassfish.jersey.media</groupId>
 *     <artifactId>jersey-media-json-jackson</artifactId>
 *     <version>2.22.1</version>
 *     <scope>test</scope>
 *   </dependency>
 *   <dependency>
 *     <groupId>commons-logging</groupId>
 *     <artifactId>commons-logging</artifactId>
 *     <version>1.2</version>
 *     <scope>test</scope>
 *   </dependency>
 *   <dependency>
 *     <groupId>org.hamcrest</groupId>
 *     <artifactId>hamcrest-all</artifactId>
 *     <version>1.3</version>
 *     <scope>test</scope>
 *   </dependency>
 * </dependencies>
 * 
 * <repositories>
 *   <repository>
 *     <id>spring-snapshots</id>
 *     <name>Spring snapshots</name>
 *     <url>https://repo.spring.io/libs-snapshot</url>
 *     <snapshots>
 *       <enabled>true</enabled>
 *     </snapshots>
 *   </repository>
 * </repositories>
 *
 * @author Paul Samsotha
 */
public class RestAssuredDocs extends JerseyTest {
    
    @Rule
    public final RestDocumentation restDocumentation 
            = new RestDocumentation("target/generated-snippets");
    
    public static class TestBean {
        public int id;
        public String message;
        public TestBean (){}
        public TestBean(int id, String message) {
            this.id = id;
            this.message = message;
        }
    }
    
    @Path("test")
    @Produces("application/json")
    @Consumes("application/json")
    public static class TestResource {
        
        @PUT
        @Path("{id}")
        public TestBean update(TestBean bean) {
            return bean;
        }
    }
    
    @Override
    public ResourceConfig configure() {
        return new ResourceConfig(TestResource.class)
                .register(new LoggingFilter(Logger.getAnonymousLogger(), true));
    }
    
    private final int port = 9998;
    private final ObjectMapper mapper = new ObjectMapper();
    
    @Test
    public void examplePut() throws Exception {
        TestBean bean = new TestBean(1, "a message");
        given().port(this.port)
                .filter(documentationConfiguration(this.restDocumentation))
                .filter(document("example-put", 
                        requestFields(
                                fieldWithPath("id").description("The id"),
                                fieldWithPath("message").description("The message")
                        ),
                        responseFields(
                                fieldWithPath("id").description("The id"),
                                fieldWithPath("message").description("The message")
                        ),
                        pathParameters(
                                parameterWithName("id").description("The id")
                        )
                ))
                .contentType("application/json")
                .accept("application/json")
                .content(mapper.writeValueAsString(bean))
                .put("/test/{id}", "1")
                .then()
                .statusCode(200)
                .body("id", equalTo(1))
                .body("message", equalTo("a message"));
    
    }
}

有关如何使用 REST Assured 的更多示例,请访问 User Guide


更新2

刚刚发布了 Jersey 的实现。您可以找到该项目here 。基本用法如下所示。请参阅项目中的 wiki 了解更多信息

依赖

<properties>
    <your.jersey.version>2.23</your.jersey.version>
    <restdocsext.jersey.version>0.1.0</restdocsext.jersey.version>
</properties>
<dependencies>
    <dependency>
        <groupId>io.github.restdocsext</groupId>
        <artifactId>restdocsext-jersey</artifactId>
        <version>${restdocsext.jersey.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${your.jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>${your.jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>${your.jersey.version}</version>
    </dependency>
</dependencies>

示例

// Other imports excluded for brevity
import static io.github.restdocsext.jersey.JerseyRestDocumentation.document;
import static io.github.restdocsext.jersey.JerseyRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders;

public class SimpleDocumentation extends JerseyTest {

    @Rule
    public JUnitRestDocumentation documentation 
            = new JUnitRestDocumentation("target/generated-snippets");

    @Path("test")
    public static class TestResource {
        @GET
        public String getSimple() {
            return "SimpleTesting";
        }
    }

    @Override
    public ResourceConfig configure() {
        return new ResourceConfig(TestResource.class);
    }

    @Test
    public void getSimple() {
        final Response response = target("test")
                .register(documentationConfiguration(this.documentation)) 
                .register(document("get-simple", 
                        preprocessRequest(removeHeaders("User-Agent")))) 
                .request()
                .get();
        assertThat(response.getStatus(), is(200));
        assertThat(response.readEntity(String.class), is("SimpleTesting"));
    }
}

关于java - 是否可以将 Spring Restdocs 与 Jersey 应用程序一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35068860/

相关文章:

java - 只是想清理它(java)

java - 允许 App Timer 在屏幕锁定时运行

java - Jersey 2.22 : Where should I define the location of REST resources?

java - 如何让 JInternalFrame 填充容器并禁用拖动功能?

java - 从空包中导入所有内容

java - Hibernate 正在提交但不保存

java - Spring 迁移到 5.0.0 替换已弃用的 WebMvcConfigurerAdapter 是错误的

java - 如何让Spring bean扩展一个通用的抽象类?

java - 将 JSON 从 Javascript 客户端发送到 Atmosphere 框架中的 Jersey 资源

java - jetty 服务器中的 REST 和静态内容