Spring Cloud 使用REST文檔生成存根

2024-01-02 16:47 更新

Spring REST Docs可用于為具有Spring MockMvc或WebTestClient或Rest Assured的HTTP API生成文檔(例如,Asciidoctor格式)。在為API生成文檔的同時(shí),還可以使用Spring Cloud Contract WireMock生成WireMock存根。為此,編寫您的常規(guī)REST Docs測試用例,并使用@AutoConfigureRestDocs在REST Docs輸出目錄中自動(dòng)生成存根。以下代碼顯示了使用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存根。它將所有GET請求與“ / resource”路徑匹配。WebTestClient相同的示例(用于測試Spring WebFlux應(yīng)用程序)看起來像這樣:

@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方法創(chuàng)建一個(gè)帶有請求匹配器的存根,以及除“主機(jī)”和“內(nèi)容長度”之外的所有標(biāo)頭。為了更精確地匹配請求(例如,匹配POST或PUT的正文),我們需要顯式創(chuàng)建一個(gè)請求匹配器。這樣做有兩個(gè)效果:

  • 創(chuàng)建僅以您指定的方式匹配的存根。
  • 斷言測試用例中的請求也匹配相同的條件。

此功能的主要入口點(diǎn)是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"));
	}
}

該合同規(guī)定,任何帶有“ id”字段的有效POST都會(huì)收到此測試中定義的響應(yīng)。您可以將對.jsonPath()的呼叫鏈接在一起以添加其他匹配器。如果不熟悉JSON Path,JayWay文檔可以幫助您快速入門此測試的WebTestClient版本具有您插入相同位置的類似的verify()靜態(tài)助手。

除了jsonPathcontentType便捷方法之外,您還可以使用WireMock API來驗(yàn)證請求是否與創(chuàng)建的存根匹配,如以下示例所示:

@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豐富。您可以通過正則表達(dá)式以及JSON路徑匹配標(biāo)頭,查詢參數(shù)和請求正文。這些功能可用于創(chuàng)建具有更廣泛參數(shù)范圍的存根。上面的示例生成一個(gè)類似于以下示例的存根:

post-resource.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()方法來創(chuàng)建請求匹配器,但是不能同時(shí)使用兩種方法。

在使用者方面,可以使本節(jié)前面部分生成的resource.json在類路徑上可用(例如,通過<< publishing-stubs-as-jars)。之后,可以使用WireMock以多種不同方式創(chuàng)建存根,包括使用@AutoConfigureWireMock(stubs="classpath:resource.json"),如本文檔前面所述。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)