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

我正在我的公司采用 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地图界面一样返回错误的请求响应?


萧十郎
浏览 134回答 1
1回答

慕田峪4524236

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。状态是抽象的——它并不暗示状态是如何配置的。它可以通过更新数据库或配置存根等多种方式实现状态转换。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go