API文档是前端与后端快速开发,减少沟通成本的必要条件,有一份完善的文档是很必要的,由通过测试来生成文档的好处就是:测试数据有了,测试返回结果有了,而且可以对这些字段进行说明,很清晰,在springboot框架里,去使用mockMvc文档生成时,需要有以下几个步骤,大叔总结了一下,分享给大家。

一 mockMvc包引用

  1. testCompile('org.springframework.restdocs:spring-restdocs-mockmvc')
  1. asciidoctor 'org.springframework.restdocs:spring-restdocs-asciidoctor'

二 snippetsDir插件引用

在buildscript块里添加如下代码

  1. maven {
    url "https://plugins.gradle.org/m2/"
    }
    mavenCentral()
    dependencies {
    classpath "org.asciidoctor:asciidoctor-gradle-jvm:2.0.0-rc.1"
  2.  
  3. }

添加插件

  1. apply plugin: "org.asciidoctor.convert"

三 配置三大路径的地址,三大路径指,asciidoctor文档路径,生成的API文档目录和snippets目录

  1. jar {
  2. dependsOn asciidoctor
  3. from ("${asciidoctor.outputDir}/html5") {
  4. into 'static/docs'
  5. }
  6. }
  7.  
  8. ext {
  9. snippetsDir = file('build/generated-snippets')
  10. }
  11.  
  12. integTest {
  13. outputs.dir snippetsDir
  14. }
  15.  
  16. asciidoctor {
    inputs.dir snippetsDir
  17. outputDir "build/asciidoc"
  18. dependsOn integTest
  19. sourceDir 'src/docs/asciidoc'
  20. }

四 添加API接口

  1. @RestController
  2. public class DocController {
  3. public static final String DOC = "/doc/{name}";
  4. public static final String DOC_LIST = "/doc/list";
  5.  
  6. @GetMapping(DOC)
  7. public Map<String, String> index(@PathVariable String name) {
  8. Map<String, String> maps = new HashMap<>();
  9. maps.put("name", "Hello");
  10. maps.put("sex", "1");
  11. maps.put("buyer", name);
  12. return maps;
  13. }
  14. }

五 添加测试用例

  1. package test.lind.javaLindDay;
  2.  
  3. import static org.hamcrest.Matchers.containsString;
  4. import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
  5. import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
  6. import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
  7. import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
  8. import static org.springframework.restdocs.payload.PayloadDocumentation.relaxedRequestFields;
  9. import static org.springframework.restdocs.payload.PayloadDocumentation.relaxedResponseFields;
  10. import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
  11. import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
  12. import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
  13. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
  14. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
  15.  
  16. import org.junit.Before;
  17. import org.junit.Rule;
  18. import org.junit.Test;
  19. import org.junit.runner.RunWith;
  20. import org.springframework.beans.factory.annotation.Autowired;
  21. import org.springframework.boot.test.context.SpringBootTest;
  22. import org.springframework.restdocs.JUnitRestDocumentation;
  23. import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
  24. import org.springframework.restdocs.payload.RequestFieldsSnippet;
  25. import org.springframework.restdocs.payload.ResponseFieldsSnippet;
  26. import org.springframework.restdocs.request.PathParametersSnippet;
  27. import org.springframework.test.context.ActiveProfiles;
  28. import org.springframework.test.context.junit4.SpringRunner;
  29. import org.springframework.test.web.servlet.MockMvc;
  30. import org.springframework.test.web.servlet.setup.MockMvcBuilders;
  31. import org.springframework.web.context.WebApplicationContext;
  32. import test.lind.javaLindDay.controller.DocController;
  33.  
  34. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  35. @ActiveProfiles("integTest")//指定profile环境
  36. @RunWith(SpringRunner.class)
  37. public class MockMvcTest {
  38. static final ResponseFieldsSnippet orderResponseFieldsParameters = relaxedResponseFields(
  39. fieldWithPath("name").description("账号"),
  40. fieldWithPath("buyer").description("购买者"),
  41. fieldWithPath("sex").description("性别")
  42. );
  43. static final RequestFieldsSnippet orderRequestFieldsParameters = relaxedRequestFields(
  44. fieldWithPath("code").description("凭证号"),
  45. fieldWithPath("word").description("凭证字"),
  46. fieldWithPath("batch").description("批次")
  47. );
  48. static final PathParametersSnippet orderRequestPathParameters = pathParameters(
  49. parameterWithName("name").description("购买者")
  50. );
  51.  
  52. @Rule
  53. public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();
  54.  
  55. protected MockMvc mockMvc;
  56.  
  57. @Autowired
  58. private WebApplicationContext context;
  59.  
  60. @Before
  61. public void setUp() {
  62. this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
  63. .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation)
  64. .uris().withScheme("http").withHost("localhost").withPort(8080)
  65. .and()
  66. .operationPreprocessors().withResponseDefaults(prettyPrint()))
  67. .build();
  68. }
  69.  
  70. @Test
  71. public void get_orders() throws Exception {
  72. this.mockMvc.perform(
  73. get(DocController.DOC, "zzl"))
  74. .andDo(print())
  75. .andExpect(status().isOk())
  76. .andExpect(content().string(containsString("Hello")))
  77. .andDo(document("doc-index", orderRequestPathParameters, orderResponseFieldsParameters));
  78. }
  79.  
  80. @Test
  81. public void get_list() throws Exception {
  82. this.mockMvc.perform(
  83. get(DocController.DOC_LIST))
  84. .andDo(print())
  85. .andExpect(status().isOk())
  86. .andDo(document("doc-list", orderResponseFieldsParameters));
  87. }
  88. }

这里有个需要注意的地址,get静态方法的包应该是import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;否则会有找不到路由的

错误,这点困扰了我很久。

六 编译,打包,它会同时去下载API DOC所需要的文件

  1. gradle build

最后,进入build/asciidoc/html5目录,浏览我们的API说明文件即可。

感谢各位的阅读!

springboot~mockMvc和asciidoctor生成基于TDD的API文档的更多相关文章

  1. 生成基于Maven的项目文档站点

    在Maven中,可以使用“mvn site”,为您的项目信息生成文档站点. mvn site 生成的网站是在项目的“target/site”文件夹中. mvn site 示例 请参见通过“mvn si ...

  2. maven 学习---生成基于Maven的项目文档站点

    在Maven中,可以使用“mvn site”,为您的项目信息生成文档站点. mvn site 生成的网站是在项目的“target/site”文件夹中. mvn site 示例 请参见通过“mvn si ...

  3. SpringBoot系列: 使用 Swagger 生成 API 文档

    SpringBoot非常适合开发 Restful API程序, 我们都知道为API文档非常重要, 但要维护好难度也很大, 原因有: 1. API文档如何能被方便地找到? 以文件的形式编写API文档都有 ...

  4. Spring Boot学习笔记 - 整合Swagger2自动生成RESTful API文档

    1.添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <!--swagger2--> <dependency> <groupId>io.spr ...

  5. Wisdom RESTClient支持自动化测试并可以生成API文档

    Wisdom REST Client V1.2 支持自动化测试RESTful API并生成精美的测试报告,同时基于历史数据自动生成精美的RESTful API文档. 工具地址:https://gith ...

  6. 利用sphinx为python项目生成API文档

    sphinx可以根据python的注释生成可以查找的api文档,简单记录了下步骤 1:安装 pip install -U Sphinx 2:在需要生成文档的.py文件目录下执行sphinx-apido ...

  7. 第十二节:WebApi自动生成在线Api文档的两种方式

    一. WebApi自带生成api文档 1. 说明 通过观察,发现WebApi项目中Area文件夹下有一个HelpPage文件夹,如下图,该文件夹就是WebApi自带的生成Api的方式,如果该文件夹没了 ...

  8. eclipse如何为java项目生成API文档、JavaDoc

    当我们的项目很大,编写了很多代码的时候,就需要生成一个标准的API文档,让后续的开发人员,或者合作者可以清晰的了解您方法的使用,那么如何将自己的项目生成API文档呢? 1.点击eclipse的[Pro ...

  9. Spring Boot 集成Swagger2生成RESTful API文档

    Swagger2可以在写代码的同时生成对应的RESTful API文档,方便开发人员参考,另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API. 使用Spring Boot可 ...

随机推荐

  1. Java Script 读书笔记 (三) 函数

    1. 函数作用域 在函数内部定义的变量,外部无法读取,称为"局部变量"(local variable). 变量v在函数内部定义,所以是一个局部变量,函数之外就无法读取. 函数内部定 ...

  2. logrus_hook.go

    package) //表示自身栈中跳过6个,:]     entry.Data["file"] = fileName     entry.Data["func" ...

  3. 【BZOJ 3561】 DZY Loves Math VI

    题目: 给定正整数n,m.求   题解: 水题有益身心健康.(博客园的辣鸡数学公式) 其实到这我想强上伯努利数,然后发现$n^2$的伯努利数,emmmmmm 发现这个式子可以算时间复杂度,emmmmm ...

  4. BZOJ_3210_花神的浇花集会_切比雪夫距离

    BZOJ_3210_花神的浇花集会_切比雪夫距离 Description 在花老师的指导下,每周4都有一个集会活动,俗称“浇水”活动. 具体浇水活动详情请见BZOJ3153 但这不是重点 花神出了好多 ...

  5. BZOJ_2124_等差子序列_线段树+Hash

    BZOJ_2124_等差子序列_线段树+Hash Description 给一个1到N的排列{Ai},询问是否存在1<=p1<p2<p3<p4<p5<…<pL ...

  6. BZOJ_1026_[SCOI2009]windy数_数位DP

    BZOJ_1026_[SCOI2009]windy数_数位DP 题意:windy定义了一种windy数.不含前导零且相邻两个数字之差至少为2的正整数被称为windy数. windy想知道, 在A和B之 ...

  7. 【源码安装】Heartbeat3.0.9

    1.概述1.1 关于Heartbeat1.2 本篇博客实践环境2. 部署基础环境2.1 通过YUM安装依赖环境2.2 创建Heartbeat用户和组3. 编译安装3.1下载源码包3.2 编译安装3.2 ...

  8. .NET 创建 classlib时,netcoreapp2.0与netstandard2.0的区别

    最近单位在开发一个新项目,在技术选型的时候,我们决定后台代码全部使用 dot net core来进行开发. 当项目引用公司之前的一个类库的时候,总是出现缺少XX组件的错误,所以我们检查了所有的类库,将 ...

  9. 理解图像分割中的卷积(Understand Convolution for Semantic Segmentation)

    以最佳的101 layer的ResNet-DUC为基础,添加HDC,实验探究了几种变体: 无扩张卷积(no dilation):对于所有包含扩张卷积,设置r=1r=1 扩张卷积(dilation Co ...

  10. 阿里云Centos7.x MySql安装教程示例

    创建用户 useradd mysql; passwd mysql; 下载(比如:5.5.61) 地址 https://dev.mysql.com/downloads/mysql/5.6.html#do ...