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

时间:2016-01-28 18:08:56

标签: java spring jersey jersey-2.0 spring-restdocs

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

如果是这样,请指点我任何相关的示例或教程。

1 个答案:

答案 0 :(得分:3)

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

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

更新

因此,在发布此答案后不久,Spring REST Docs将已确认分支与主分支合并,因此您现在可以使用spring-restdocs-restassured工件的SNAPSHOT,而无需自己构建项目。您只需添加Spring Snapshot存储库即可。以下是使用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"));
    }
}