您现在的位置是:主页 > news > 垦利县建设局网站/太仓网站制作

垦利县建设局网站/太仓网站制作

admin2025/6/23 9:02:21news

简介垦利县建设局网站,太仓网站制作,网站建设与维护需要,规划排版网站这篇文章将带你了解如何用spring官方推荐的restdoc去生成api文档。本文创建一个简单的springboot工程,将http接口通过Api文档暴露出来。只需要通过 JUnit单元测试和Spring的MockMVC就可以生成文档。完整项目的源码来源 技术支持一七九一七四三三八零 准备工作 你需要…

垦利县建设局网站,太仓网站制作,网站建设与维护需要,规划排版网站这篇文章将带你了解如何用spring官方推荐的restdoc去生成api文档。本文创建一个简单的springboot工程,将http接口通过Api文档暴露出来。只需要通过 JUnit单元测试和Spring的MockMVC就可以生成文档。完整项目的源码来源 技术支持一七九一七四三三八零 准备工作 你需要…

这篇文章将带你了解如何用spring官方推荐的restdoc去生成api文档。本文创建一个简单的springboot工程,将http接口通过Api文档暴露出来。只需要通过 JUnit单元测试和Spring的MockMVC就可以生成文档。完整项目的源码来源 技术支持一七九一七四三三八零

准备工作

你需要15min

Jdk 1.8

maven 3.0+

idea

创建工程

引入依赖,其pom文件:

通过@SpringBootApplication,开启springboot

<dependencies><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.restdocs</groupId><artifactId>spring-restdocs-mockmvc</artifactId><scope>test</scope></dependency></dependencies>
复制代码

通过@SpringBootApplication,开启springboot

@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
复制代码

在springboot通常创建一个controller:

@RestController
public class HomeController {``@GetMapping("/")public Map<String, Object> greeting() {return Collections.singletonMap("message", "Hello World");}}
复制代码

启动工程,访问localhost:8080,浏览器显示:

{“message”:”Hello World”}
复制代码

证明接口已经写好了,但是如何通过restdoc生存api文档呢

Restdoc,通过单元测试生成api文档 restdocs是通过单元测试生存snippets文件,然后snippets根据插件生成htm文档的。

建一个单元测试类:

@RunWith(SpringRunner.class)
@WebMvcTest(HomeController.class)
@AutoConfigureRestDocs(outputDir = "target/snippets")
public class WebLayerTest {@Autowiredprivate MockMvc mockMvc;@Testpublic void shouldReturnDefaultMessage() throws Exception {this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk()).andExpect(content().string(containsString("Hello World"))).andDo(document("home"));}
}
复制代码

其中,@ AutoConfigureRestDocs注解开启了生成snippets文件,并指定了存放位置。

启动单元测试,测试通过,你会发现在target文件下生成了一个snippets文件夹,其目录结构如下:

└── target└── snippets└── home└── httpie-request.adoc└── curl-request.adoc└── http-request.adoc└── http-response.adoc
复制代码

默认情况下,snippets是Asciidoctor格式的文件,包括request和reponse,另外其他两种httpie和curl两种流行的命令行的http请求模式。 到目前为止,只生成了Snippets文件,需要用Snippets文件生成文档。