使用 REST Docs
您可以使用 Spring REST Docs 为 HTTP API 生成文档(例如,采用 Asciidoc 格式),使用 Spring MockMvc 或 WebTestClient。在为 API 生成文档的同时,您还可以使用 Spring Cloud Contract WireMock 生成 WireMock 存根。为此,编写您的常规 REST Docs 测试用例,并使用 @AutoConfigureRestDocs 自动在 REST Docs 输出目录中生成存根。以下 UML 图显示了 REST Docs 的流程
以下示例使用 MockMvc
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureRestDocs(outputDir = "target/snippets")
@AutoConfigureMockMvc
public class ApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
public void contextLoads() throws Exception {
mockMvc.perform(get("/resource"))
.andExpect(content().string("Hello World"))
.andDo(document("resource"));
}
}
此测试会在 target/snippets/stubs/resource.json 生成一个 WireMock 存根。它匹配所有对 /resource 路径的 GET 请求。使用 WebTestClient(用于测试 Spring WebFlux 应用程序)的相同示例如下
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureRestDocs(outputDir = "target/snippets")
@AutoConfigureWebTestClient
public class ApplicationTests {
@Autowired
private WebTestClient client;
@Test
public void contextLoads() throws Exception {
client.get().uri("/resource").exchange()
.expectBody(String.class).isEqualTo("Hello World")
.consumeWith(document("resource"));
}
}
在没有任何额外配置的情况下,这些测试会创建一个存根,其中包含一个用于 HTTP 方法和除 host 和 content-length 之外的所有请求头的请求匹配器。要更精确地匹配请求(例如,匹配 POST 或 PUT 的请求体),我们需要显式地创建一个请求匹配器。这样做有两个效果
-
创建一个仅以您指定的方式进行匹配的存根。
-
断言测试用例中的请求也匹配相同的条件。
此功能的主要入口点是 WireMockRestDocs.verify(),它可以替代 document() 便利方法,示例如下
import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureRestDocs(outputDir = "target/snippets")
@AutoConfigureMockMvc
public class ApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
public void contextLoads() throws Exception {
mockMvc.perform(post("/resource")
.content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
.andExpect(status().isOk())
.andDo(verify().jsonPath("$.id"))
.andDo(document("resource"));
}
}
上述契约指定任何包含 id 字段的有效 POST 请求都会收到此测试中定义的响应。您可以将 .jsonPath() 的调用链式连接起来以添加额外的匹配器。如果您不熟悉 JSON Path,JayWay 文档可以帮助您快速上手。此测试的 WebTestClient 版本具有类似的 verify() 静态辅助方法,您可以将其插入到相同的位置。
除了 jsonPath 和 contentType 便捷方法之外,您还可以使用 WireMock API 来验证请求是否与创建的存根匹配,示例如下
@Test
public void contextLoads() throws Exception {
mockMvc.perform(post("/resource")
.content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
.andExpect(status().isOk())
.andDo(verify()
.wiremock(WireMock.post(urlPathEquals("/resource"))
.withRequestBody(matchingJsonPath("$.id"))
.andDo(document("post-resource"))));
}
WireMock API 功能丰富。您可以通过正则表达式以及 JSON 路径来匹配请求头、查询参数和请求体。您可以使用这些功能创建具有更广泛参数范围的存根。上面的示例生成了一个类似于下面示例的存根
{
"request" : {
"url" : "/resource",
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$.id"
}]
},
"response" : {
"status" : 200,
"body" : "Hello World",
"headers" : {
"X-Application-Context" : "application:-1",
"Content-Type" : "text/plain"
}
}
}
您可以使用 wiremock() 方法或 jsonPath() 和 contentType() 方法来创建请求匹配器,但不能同时使用这两种方法。 |
在消费者端,您可以将本节前面生成的 resource.json 文件在类路径上可用(例如,通过将存根发布为 JAR)。之后,您可以通过多种不同方式创建使用 WireMock 的存根,包括使用 @AutoConfigureWireMock(stubs="classpath:resource.json"),如本文档前面所述。
| 在 Spring Cloud Contract 5.0.x 中,对 Spring Rest Docs 中 Rest Assured 的支持已移除,原因是 Rest Assured 与 Groovy 5 不兼容。 |
使用 REST Docs 生成契约
您还可以使用 Spring REST Docs 生成 Spring Cloud Contract DSL 文件和文档。如果将其与 Spring Cloud WireMock 结合使用,您将同时获得契约和存根。
您为什么要使用此功能?社区中的一些人提出了一个问题,他们希望转向基于 DSL 的契约定义,但他们已经有很多 Spring MVC 测试。使用此功能可以生成契约文件,您可以稍后修改并将它们移动到(您的配置中定义的)文件夹中,以便插件找到它们。
| 您可能想知道为什么此功能在 WireMock 模块中。此功能在那里是因为生成契约和存根都是有意义的。 |
考虑以下测试
this.mockMvc
.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
.andExpect(status().isOk())
.andExpect(content().string("bar"))
// first WireMock
.andDo(WireMockRestDocs.verify()
.jsonPath("$[?(@.foo >= 20)]")
.jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
.contentType(MediaType.valueOf("application/json")))
// then Contract DSL documentation
.andDo(document("index", SpringCloudContractRestDocs.dslContract(Maps.of("priority", 1))));
上述测试创建了上一节中介绍的存根,同时生成了契约和文档文件。
契约名为 index.groovy,可能类似于以下示例
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method 'POST'
url '/foo'
body('''
{"foo": 23 }
''')
headers {
header('''Accept''', '''application/json''')
header('''Content-Type''', '''application/json''')
}
}
response {
status OK()
body('''
bar
''')
headers {
header('''Content-Type''', '''application/json;charset=UTF-8''')
header('''Content-Length''', '''3''')
}
bodyMatchers {
jsonPath('$[?(@.foo >= 20)]', byType())
}
}
}
生成的文档(在本例中采用 Asciidoc 格式)包含一个格式化的契约。此文件的位置将是 index/dsl-contract.adoc。
指定优先级属性
方法 SpringCloudContractRestDocs.dslContract() 接受一个可选的 Map 参数,允许您在模板中指定额外的属性。
其中一个属性是优先级字段,您可以按如下方式指定
SpringCloudContractRestDocs.dslContract(Map.of("priority", 1))
覆盖 DSL 契约模板
默认情况下,契约的输出基于名为 default-dsl-contract-only.snippet 的文件。
您可以提供一个自定义模板文件,方法是覆盖 getTemplate() 方法,如下所示
new ContractDslSnippet(){
@Override
protected String getTemplate() {
return "custom-dsl-contract";
}
}));
所以上面显示这一行的例子
.andDo(document("index", SpringCloudContractRestDocs.dslContract()));
应改为
.andDo(document("index", new ContractDslSnippet(){
@Override
protected String getTemplate() {
return "custom-dsl-template";
}
}));
模板通过在类路径上查找资源来解析。按顺序检查以下位置
-
org/springframework/restdocs/templates/${templateFormatId}/${name}.snippet -
org/springframework/restdocs/templates/${name}.snippet -
org/springframework/restdocs/templates/${templateFormatId}/default-${name}.snippet
因此,在上面的例子中,您应该将一个名为 custom-dsl-template.snippet 的文件放置在 src/test/resources/org/springframework/restdocs/templates/custom-dsl-template.snippet 中