如何在wiremock-pact-generator中添加Pact场景状态(provider_state)
问题描述
我们使用wiremock-pact-generator生成Pact合约文件,但未找到该库处理场景状态的方式。此前通过pactdslwithprovider可以设置状态,现在希望用wiremock-pact-generator实现同样功能。
已为MockServer添加wiremock-pact-generation监听器,相关代码如下:
@BeforeAll public static void setup() { mockServer = new WireMockServer(options().port(1080).extensions(new ResponseTemplateTransformer(true))); mockServer.addMockServiceRequestListener( WireMockPactGenerator.builder("product-service-consumer", "producte-service-provider").build()); mockServer.start(); }
当前使用的WireMock stub配置:
{ "request" : { "urlPathPattern" : "/products/1001", "method" : "GET" }, "response" : { "status" : 200, "body" : "{\"productId\":1001,\"name\": \"Dell Laptop\",\"description\": \"Warranty expiring soon\"}", "headers" : { "X-Application-Context" : "application:-1", "Content-Type" : "application/json" }, "transformers" : [ "response-template" ] } }
生成的Pact合约文件中interactions缺少provider_state字段,希望添加"provider_state": "Fetch Product for Id 1001",请问该如何配置?
解决方案
wiremock-pact-generator支持通过WireMock stub的**元数据(metadata)**来指定provider状态,具体配置方式如下:
1. 修改JSON格式的Stub配置
在stub的根节点添加metadata字段,指定pact相关配置,其中包含providerState:
{ "request" : { "urlPathPattern" : "/products/1001", "method" : "GET" }, "response" : { "status" : 200, "body" : "{\"productId\":1001,\"name\": \"Dell Laptop\",\"description\": \"Warranty expiring soon\"}", "headers" : { "X-Application-Context" : "application:-1", "Content-Type" : "application/json" }, "transformers" : [ "response-template" ] }, "metadata": { "pact": { "providerState": "Fetch Product for Id 1001" } } }
2. 若使用Java代码定义Stub
如果是通过Java API创建WireMock stub,可通过withMetadata()方法添加对应配置:
stubFor(get(urlPathEqualTo("/products/1001")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\"productId\":1001,\"name\": \"Dell Laptop\",\"description\": \"Warranty expiring soon\"}") .withTransformer("response-template")) .withMetadata(Map.of( "pact", Map.of("providerState", "Fetch Product for Id 1001") )));
配置完成后,重新运行测试,生成的Pact合约文件中对应的interaction就会包含provider_state字段。
内容的提问来源于stack exchange,提问作者Gurubabu
相关产品推荐
相关产品推荐

