0

我是 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 中已经有一个包含这个 rest 调用的以前的 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)

问题):

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

  2. 在 - 的里面:

    .andDo(document("{class-name}/{method-name}"));

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

  1. 我认为我不需要运行tomcat(使用以前的war文件)?

抱歉,从未使用过 Spring Rest Docs,只是希望有人能指出我正确的方向......

4

0 回答 0