4

我的测试课是

   package com.htc.spring.rest.docs;
   -------
   @RunWith(SpringJUnit4ClassRunner.class)
   @SpringApplicationConfiguration(classes=CrudRestDemoApplication.class)
   @WebAppConfiguration
   @IntegrationTest
   public class ForRestDocumentationTest {

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

   private final ObjectMapper objectMapper = new ObjectMapper();

   @Autowired
   public  EmbeddedWebApplicationContext context;//or WebApplicationContext

   private MockMvc mockMvc;

   public ForRestDocumentationTest(){
   System.out.println("Test class created");
   }

   @Before
   public void setup(){
     this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
    .apply(documentationConfiguration(this.restDoc)).alwaysDo(document("
     {method-name}/{step}/")).build();


   }

   @Test
   public void addOrder() throws Exception {
     GregorianCalendar calendar = new 
        GregorianCalendar(2015,Calendar.MARCH,21); 
      OrderTO newOrder = 
        new OrderTO(8000, calendar.getTime(), "M/s Joseph Sales", 2120.5);

        this.mockMvc.perform(post("/orders")
            .accept(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(newOrder))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(document("index"));
        } 


     @Test
     public void getOrder() throws Exception {
      System.out.println("get order fired");
      int orderId = 2000;     
       this.mockMvc.perform(get("/orders/{orderId}", orderId)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("orderId").isNotEmpty())
            .andExpect(jsonPath("orderDate").isNotEmpty())
            .andExpect(jsonPath("customer").isNotEmpty())
            .andExpect(jsonPath("cost").isNotEmpty())
            .andDo(document("index"));
         }
     @Test
     public void getAllOrders() throws Exception {

      this.mockMvc.perform(get("/orders")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$").isArray())
            .andExpect(jsonPath("[*].orderId").isNotEmpty())
            .andExpect(jsonPath("[*].orderDate").isNotEmpty())
            .andExpect(jsonPath("[*].custoer").isNotEmpty())
            .andExpect(jsonPath("[*].cost").isNotEmpty())
            .andDo(document("index"));
      }
      private static final String ORDERS_ORDERID_DESCRIPTION = 
               "OrderTO's OrderId";
      private static final String ORDERS_ORDER_DATE_DESCRIPTION = 
                    "OrderTO's Order Date";

      private static final String ORDERS_CUSTOMER_DESCRIPTION = 
                              "OrderTO's Customer";
      private static final String ORDERS_COST_DESCRIPTION =

      "OrderTO's Cost";       

     }

pom.xml

   <?xml version="1.0" encoding="UTF-8"?>
    ---------
   <groupId>sprRestDocs</groupId>
   <artifactId>sprRestDocs</artifactId>
   <version>1.0.0</version>
   <packaging>war</packaging>

    <name>sprRestDocs</name>
    <url>http://maven.apache.org</url>
     <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.3.6.RELEASE</version>
       <relativePath/> 
     </parent>


    <properties>
       <java.version>1.8</java.version>
       <springframework.version>4.3.0.RELEASE
         </springframework.version>
       <jackson.library>2.8.0</jackson.library>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <snippetsDirectory>target/generated-snippets
        </snippetsDirectory>
       </properties>

       <dependencies>
          <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-hateoas</artifactId>
          </dependency>
         <dependency>
          <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
         </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${springframework.version}</version>                   
        </dependency>

        <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
        </dependency>
        <dependency>
           <groupId>javax.servlet.jsp</groupId>
           <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
         </dependency>
         <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-databind</artifactId>
             <version>${jackson.library}</version>
         </dependency>
         <dependency>
           <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>${jackson.library}</version>
           </dependency>    
          <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
              <artifactId>jackson-core</artifactId>
              <version>${jackson.library}</version>
           </dependency>    
           <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-annotations</artifactId>
              <version>${jackson.library}</version>
            </dependency>   

            <dependency>
              <groupId>com.jayway.jsonpath</groupId>
               <artifactId>json-path</artifactId>
               <scope>test</scope>
              </dependency>

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

              <dependency> 
                <groupId>org.springframework.restdocs</groupId>
                <artifactId>spring-restdocs-core</artifactId>
                <version>1.1.0.RELEASE</version>
                 <scope>test</scope> 
               </dependency>
               <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
              </dependency>     
          </dependencies>
        <build>
          <finalName>sprRestDocs</finalName>
          <plugins>
               <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
           </plugin>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.2</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                    <warName>sprRestDocs</warName>
             <failOnMissingWebXml>false</failOnMissingWebXml>
               </configuration>
            </plugin>
            <plugin> 
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-surefire-plugin</artifactId>
               <version>2.19.1</version>            
              <configuration>
                <includes>
                   <include>>**/*Test.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>
                <attributes>
                  <snippets>${snippetsDirectory}</snippets> 
                </attributes>
            </configuration>
            </execution>
           </executions>
         </plugin>
         <plugin> 
             <artifactId>maven-resources-plugin</artifactId>
             <version>2.7</version>
         <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>

        <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>
     </project>

如果我使用mvn spring-boot:run没有文档生成。

如果我使用mvn integration-test我会得到 api-guide.adoc [html 文件] 但没有片段

如果我尝试运行, mvn -Dtest=com.htc.spring.rest.docs.ForRestDocumentationTest test 我会收到此错误:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.htc.spring.rest.docs.ForRestDocumentationTest
17:33:12.463 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.htc.spring.rest.docs.ForRestDocumentationTest]
17:33:12.463 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
17:33:12.479 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.383 sec <<< FAILURE! - in com.htc.spring.rest.docs.ForRestDocumentationTest
initializationError(com.htc.spring.rest.docs.ForRestDocumentationTest)  Time elapsed: 0 sec  <<< ERROR!
java.lang.IllegalStateException: Could not load TestContextBootstrapper [null]. Specify @BootstrapWith's 'value' attribute or make the default bootstrapper class available.
Caused by: java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/util/Set;
4

1 回答 1

0

嗨,我自己也面临同样的问题,我找到了一个解决方案,因此正在创建片段,方法是从

<phase>prepare-package</phase> 

<phase>generate-resources</phase>

但仍然面临一个问题,即在生成 html 后会创建代码段,这就是为什么它不包含在 html 中的原因。

虽然我仍在研究那部分,但现在有一个临时解决方案,首先我执行 mvn clean test 然后一旦生成片段再次执行 mvn test并生成正确的 html doc get。这不是一个干净的解决方案,我仍在寻找一个更好的解决方案来解决这个问题,但它现在已经完成了工作。

于 2016-11-23T05:10:24.560 回答