我在我的公司致力于采用Pact,但在Golang上,我们遇到了一个基本问题,即一个消费者作为两个州的一个端点:

  • 给定("存在id为1的产品").
  • 给定("id为2的产品不存在").

我们的问题在于"不存在"这个案子.

消费者

mock供应商.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.Verify供应商(t, VerifyRequest{
        供应商BaseURL:            "http://localhost:8080",
        供应商:                   "ms.pact-provider-example-for-go",
        供应商Version:            "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 供应商StateV3) (供应商StateV3Response, error) {
                …
                return response, nil
            },
            "A product with id 2 doesn't exists": func(setup bool, s 供应商StateV3) (供应商StateV3Response, error) {
                // ???
            },
        },
    })

    require.NoError(t, err)
}

问题

供应商StateV3Response是一个映射接口时,我们如何返回错误的请求响应?

推荐答案

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.

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

Go相关问答推荐

如何在使用中介资源时处理函数中的`defer`

埃拉托塞尼筛:加快交叉关闭倍数步骤

Golang String

如何为循环扫描的bufio scanner 设置超时?

为什么 Go 对于长度为 100k 的切片使用的内存比长度为 100k 的数组要少?

nixOS 上的 Nginx 反向代理在try 加载 css/js 时返回 404

在golang中以JSON格式获取xwwwformurlencoded请求的嵌套键值对

下载和合并时输出文件已损坏

MQTT 客户端没有收到另一个客户端发送的消息

Golang:如何判断通过缓冲通道进行通信时生产者或消费者是否较慢?

如何在切片增长时自动将切片的新元素添加到函数参数

查找、解析和验证邮箱地址

如何使用 Status 字段创建 Kubernetes 对象?

每 N 秒运行一次函数,上下文超时

如何在循环中旋转图像以便在 golang 中创建 GIF?

HCL 解码:具有多个标签的块

gqlgen go,通过添加一个解析器来减少数据库调用

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

如何将类型转换为字节数组golang

为什么 Go 不允许将一个泛型分配给另一个泛型?