如何在Golang中使用pact-go为XML响应编写DSL匹配器
在 pact-go 中为 XML 响应编写 DSL 匹配器
目前 pact-go 的官方文档里确实没有针对 XML 响应匹配的直接示例,但可以通过以下两种方式实现:
方式一:拼接XML字符串结合通用匹配器
构造预期的XML结构,将需要动态匹配的字段替换为 pact-go 提供的匹配器生成值,示例代码如下:
package main import ( "github.com/pact-foundation/pact-go/v2/matchers" "github.com/pact-foundation/pact-go/v2/pact" "github.com/pact-foundation/pact-go/v2/request" "github.com/pact-foundation/pact-go/v2/response" ) func setupPactTest() { pact := pact.NewPact(pact.WithConsumer("UserServiceConsumer"), pact.WithProvider("UserServiceProvider")) // 构造带匹配规则的XML响应预期 expectedXML := ` <user> <id>` + matchers.Integer(123).Generate() + `</id> <name>` + matchers.String("John Doe").Generate() + `</name> <email>` + matchers.Regex(`user\d+@example\.com`, "user123@example.com").Generate() + `</email> </user> ` // 定义交互 pact. AddInteraction(). Given("a user with ID 1 exists"). UponReceiving("a GET request to fetch user details"). WithRequest(request.Request{ Method: "GET", Path: "/users/1", }). WillRespondWith(response.Response{ Status: 200, Headers: map[string]string{"Content-Type": "application/xml"}, Body: expectedXML, }) }
这种方式中,匹配器的Generate()方法会生成符合规则的占位值,pact会自动记录对应的匹配规则,实际测试时会验证响应XML是否符合这些规则。
方式二:使用结构化XML匹配器(部分版本支持)
部分新版本的 pact-go 内置了Xml匹配器,可以通过map结构描述XML节点,直接为节点值指定匹配器,示例代码如下:
package main import ( "github.com/pact-foundation/pact-go/v2/matchers" "github.com/pact-foundation/pact-go/v2/pact" "github.com/pact-foundation/pact-go/v2/request" "github.com/pact-foundation/pact-go/v2/response" ) func setupPactTest() { pact := pact.NewPact(pact.WithConsumer("UserServiceConsumer"), pact.WithProvider("UserServiceProvider")) // 用结构化方式定义XML匹配规则 expectedBody := matchers.Xml(map[string]interface{}{ "user": map[string]interface{}{ "id": matchers.Integer(123), "name": matchers.String("John Doe"), "email": matchers.Regex(`user\d+@example\.com`, "user123@example.com"), }, }) // 定义交互 pact. AddInteraction(). Given("a user with ID 1 exists"). UponReceiving("a GET request to fetch user details"). WithRequest(request.Request{ Method: "GET", Path: "/users/1", }). WillRespondWith(response.Response{ Status: 200, Headers: map[string]string{"Content-Type": "application/xml"}, Body: expectedBody, }) }
如果当前使用的 pact-go 版本不支持Xml匹配器,建议升级到最新稳定版尝试。
注意事项
- 若XML节点顺序有严格要求,pact默认会严格校验;若需忽略顺序,可结合
matchers.SomethingLike或正则匹配整段XML片段。 - 测试前可打印生成的预期XML,确认匹配器占位值的语法正确性,避免XML格式错误。
内容的提问来源于stack exchange,提问作者shadman140
相关产品推荐
相关产品推荐

