How to test randomly generated value in PACT.net

33 Views Asked by At

I have an API provder at http:///pay. This API accepts a POST method with a body like this:

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

and if everything is correct it gives a response like this:

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

I created a consumer test in this way:

[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);
    });
}

I thought the id returned from the mocked Pay method would be equal to the id I generated for paymentResponse(line 4). Unfortunately, inside the Pay method, a new random GUUID is generated for the id, so at the assert moment, paymentGatewayClientResponse.id is different from paymentResponse.id.

Am I missing something in the reasoning?

Sure a possible solution would be to force paymentResponse.id = paymentGatewayClientResponse.id and then assert but it looks a little bit as cheating.

1

There are 1 best solutions below

0
Matthew Fellows On

Is it failing on the consumer or provider test? The consumer test should be deterministic and should mock the API precisely.

If it's failing in the consumer test then loosen your expectation. Do you need to assert the exact value or is knowing that it generated a uuid enough?

If it's failing on the provider test you should use a matcher rather than expecting an exact value such as a regex: https://github.com/pact-foundation/pact-net/blob/09ee8189a3dba1c47a02e571e8872924b90caaa8/src/PactNet.Abstractions/Matchers/RegexMatcher.cs