如何在 PACT.net 中测试随机生成的值

问题描述 投票:0回答:1

我有一个 API 提供商,网址为 http:///pay。该 API 接受具有如下正文的 POST 方法:

{
    "amount": 115,
    "currency" "EUR"
}

如果一切正确,它会给出如下响应:

{
    "id":"4f34e5ef-80c0-4696-8d2c-4cc755b31861",
    "status":true,
    "description":""
}

我用这种方式创建了一个消费者测试:

[Fact]
public async void PaymentIsOk()
{
    PaymentRequest paymentRequest = new PaymentRequest(115, "EUR");
    PaymentResponse paymentResponse =  new PaymentResponse {id = Guid.NewGuid().ToString(), status = true};

    this.pactBuilder
        .UponReceiving("a request for paying an order")
            .WithRequest(HttpMethod.Post, "/pay")
            .WithHeader("Content-Type", "application/json")
            .WithJsonBody(paymentRequest)
        .WillRespond()
            .WithStatus(HttpStatusCode.OK)
            .WithJsonBody(paymentResponse);

    this.pactBuilder.Verify(ctx =>
    {
        // Act
        var paymentGatewayClient = new PaymentGatewayClient(ctx.MockServerUri.ToString());
        var paymentGatewayClientResponse = paymentGatewayClient.Pay(paymentRequest);

        // Assert
        // how can I test for Id?
        Assert.Empty(paymentGatewayClientResponse.description);
        Assert.True(paymentGatewayClientResponse.status);
    });
}

我认为从模拟的

Pay
方法返回的 id 将等于我为
paymentResponse
(第 4 行)生成的 id。不幸的是,在 Pay 方法内部,为 id 生成了一个新的随机 GUID,因此在断言时刻,
paymentGatewayClientResponse.id
paymentResponse.id
不同。

我在推理中遗漏了什么吗?

当然,一个可能的解决方案是强制

paymentResponse.id = paymentGatewayClientResponse.id
然后断言,但这看起来有点作弊。

c# .net pact
1个回答
0
投票

它是否未通过消费者或提供商测试?消费者测试应该是确定性的,并且应该精确地模拟 API。

如果提供商测试失败,您应该使用匹配器,而不是期望一个精确值,例如正则表达式:https://github.com/pact-foundation/pact-net/blob/09ee8189a3dba1c47a02e571e8872924b90caaa8/src/PactNet.Abstractions /匹配器/RegexMatcher.cs

© www.soinside.com 2019 - 2024. All rights reserved.