如何在 Go 中使用 Pact return 一个错误的请求 (400, 500)?

How to return a bad request (400, 500) with Pact in Go?

我正在努力在我的公司采用 Pact,但在 Golang 上,我们在一个消费者作为一个端点的 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)
}

问题

我们怎么能return一个糟糕的请求响应,因为ProviderStateV3Response是一个映射接口?

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

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