为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Go 中的 Pact 返回错误请求 (400, 500)?

如何使用 Go 中的 Pact 返回错误请求 (400, 500)?

Go
萧十郎 2022-12-05 16:41:04
我正在我的公司采用 Pact,但在 Golang 上,我们在基本情况下遇到了障碍,即消费者作为一个端点的 2 个状态:Given("存在 id 为 1 的产品").Given("ID 为 2 的产品不存在").我们的麻烦在于不存在的情况。消费者mockProvider.AddInteraction().            Given("The product with ID 66 doesn't exists").            UponReceiving("a request Product 66").            WithRequest(http.MethodGet, S("/api/v1/product/66")).            WillRespondWith(http.StatusNotFound).供应商func TestContract(t *testing.T) {    SetLogLevel("TRACE")    verifier := HTTPVerifier{}    err := verifier.VerifyProvider(t, VerifyRequest{        ProviderBaseURL:            "http://localhost:8080",        Provider:                   "ms.pact-provider-example-for-go",        ProviderVersion:            "example",                                            // os.Getenv("APP_SHA"),        BrokerURL:                  "https://…", // os.Getenv("PACT_BROKER_BASE_URL"),        PublishVerificationResults: false,        StateHandlers: StateHandlers{            "A product with id 1 exists": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {                …                return response, nil            },            "A product with id 2 doesn't exists": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {                // ???            },        },    })    require.NoError(t, err)}问题我们如何像ProviderStateV3Response地图界面一样返回错误的请求响应?
查看完整描述

1 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

StateHandlers不直接更改响应(这可能会影响测试的有效性),它们的存在是为了修改当前测试的提供者的内部状态。使用状态名称(以及可选的参数)来确定应该配置什么状态。


当测试执行时,提供者应该在适当的状态下执行其通常的代码,并做出相应的响应。


        StateHandlers: StateHandlers{

            "A product with id 1 exists": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {

                // modify internal state of the provider, so that product with ID 1 exists in the database

                return response, nil

            },

            "A product with id 2 doesn't exists": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {

                // modify internal state of the provider, so that product with ID 2 does not exist in the database

            },

        },

存储库中有示例,例如https://github.com/pact-foundation/pact-go/blob/master/examples/mux/provider/user_service_test.go#L94-L120。


状态是抽象的——它并不暗示状态是如何配置的。它可以通过更新数据库或配置存根等多种方式实现状态转换。


查看完整回答
反对 回复 2022-12-05
  • 1 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号