Spring Rest Docs - 如何从SpringMVC app

时间:2017-06-22 05:44:33

标签: spring maven spring-mvc asciidoctor spring-restdocs

Spring Rest Docs的新手......有一个预先存在的代码库,它是用Spring MVC编写的(不是Spring Boot)。

我的pom.xml中的一些摘录如下:

<properties>
    <snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <version>1.2.1.RELEASE</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12</version>
            <configuration>
                <includes>
                    <include>**/*Documentation.java</include>
                </includes>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.asciidoctor</groupId>
            <artifactId>asciidoctor-maven-plugin</artifactId>
            <version>1.5.3</version>
            <executions>
                <execution>
                    <id>generate-docs</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>process-asciidoc</goal>
                    </goals>
                    <configuration>
                        <backend>html</backend>
                        <doctype>book</doctype>
                        <sourceDocumentName>index.adoc</sourceDocumentName>
                        <attributes>
                            <snippets>${snippetsDirectory}</snippets>
                        </attributes>
                    </configuration>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.restdocs</groupId>
                    <artifactId>spring-restdocs-asciidoctor</artifactId>
                    <version>1.2.1.RELEASE</version>
                </dependency>
            </dependencies>
        </plugin>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy-resources</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.outputDirectory}/static/docs</outputDirectory>
                        <resources>
                            <resource>
                                <directory>${project.build.directory}/generated-docs</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>

有一个示例Web服务(使用SpringMVC),它发出一个简单的GET请求:

package com.myapp.rest.controllers;

@Controller
@RequestMapping("/v2")
public class MyController {

        @RequestMapping(value="users/{userId}",method=RequestMethod.GET)
        public @ResponseBody Object getUserDetails(@PathVariable String userId){
            Object response=null;
            UserDAO dao = UserDAO.getInstance();
            response=dao.getUser(userId);
            return response;
        }
}

使用curl调用此方法:

curl -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://localhost:8080/myapp/v2/users/123

返回以下有效内容:

{
    "device": "D045453",
    "userId": "123",
    "userDetails": 
    [
        {
            "propertyName": "Position",
            "propertyValue": "Manager"
        },

        {
            "propertyName": "Salary",
            "propertyValue": "120000"
        },

        {
            "propertyName": "Name",
            "propertyValue": "John Smith"
        }
    ]
}

设置我的MockMvc测试用例如下:

WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:**/mvc-dispatcher-servlet.xml")
public class MyControllerDocumentation {

    private static final String USER_ID = "123";

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

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
                .apply(documentationConfiguration(this.restDocumentation)).build();
    }

    @Test
    public void getUserDetails() throws Exception {
        this.mockMvc.perform(get("/v2/users/{userId}", USER_ID)
                    .contentType(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("device").isNotEmpty())
                    .andDo(document("{class-name}/{method-name}"));
    }
}

mvc-dispatcher-servlet.xml(位于src / main / webapp / WEB-INF)中没有applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/util
            http://www.springframework.org/schema/util/spring-util.xsd">
       <context:component-scan base-package="com.myapp.rest.controllers" />
       <mvc:annotation-driven />

       <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix">
                <value>/WEB-INF/pages/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
    </bean>
</beans>

我启动tomcat(因为我已经在$ CATALINA_HOME / webapps中有一个包含此休息调用的war文件)并且在尝试构建war文件时:

mvn clean install

这是Surefire报告中提出的内容:

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.638 sec <<< FAILURE!
    getUserDetails(com.myapp.rest.controllers.MyControllerDocumentation)  Time elapsed: 0.2 sec  <<< FAILURE!
        java.lang.AssertionError: Status expected:<200> but was:<404>
            at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
            at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
            at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665)
            at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
            at om.myapp.rest.controllers.MyControllerDocumentation.getUserDetails(MyControllerDocumentation.java:49)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:606)

问题(S):

  1. 如何从单元测试中获取简单的HTTP 200?这是配置问题吗?

  2. 内部:

    .andDo(文件(&#34; {类名} / {方法名}&#34));

  3. 如何设置它以使用Spring Rest Docs记录响应JSON有效负载中的各种属性(键/值对)?

    1. 我认为我不需要运行tomcat(使用之前的war文件)?
    2. 抱歉,从未使用过Spring Rest Docs,只是希望有人能指出我正确的方向......

0 个答案:

没有答案