pactpact-net

How do I use Like or SomethingLike in a C# Pact test?


My very first Pact test validates that the response is 200 OK, but I'd like to add tests that verify the schema of the JSON response. It seems that like or maybe SomethingLike is the solution but I don't know where in my test to use it. (See the last comment in the code below.)

   var pact = Pact.V4("WidgetsApiConsumer", "WidgetsApi", new PactConfig { LogLevel = PactLogLevel.Debug });

   var pactBuilder = pact.WithHttpInteractions();
   pactBuilder
      .UponReceiving("A GET request to retrieve widgets")
      .Given("There is more than one widget")
      .WithRequest(HttpMethod.Get, "/Widgets")
      .WillRespond()
      .WithStatus(HttpStatusCode.OK)
      .WithHeader("Content-Type", "application/json; charset=utf-8")
      .WithJsonBody(new[] {
      new
      {
         id = "B9CE5196-72F8-4FD7-B7CC-405FF62E8793",
         description = "Widget No.1"
      },
      new
      {
         id = "7F236BA3-D0D1-47F1-B379-71A3ABD46302",
         description = "Widget No.2"
      },
      });

   await pactBuilder.VerifyAsync(async ctx =>
   {
      var client = new HttpClient { BaseAddress = ctx.MockServerUri };
      var response = await client.GetAsync("/Widgets");

      response.Should().NotBeNull();
      response.IsSuccessStatusCode.Should().BeTrue();

      // Validate JSON schema
      var responseBody = await response.Content.ReadAsStringAsync();
      var widgetsContainer = JsonSerializer.Deserialize<WidgetsContainer>(responseBody, JsonSerializerOptions.Web);
      widgetsContainer.Should().NotBeNull();
      var widgets = widgetsContainer.Widgets;
      widgets.Should().NotBeNull();
      widgets.Count.Should().Be(2);
      // Assert that the ID is a valid GUID, not necessarily "B9CE5196-72F8-4FD7-B7CC-405FF62E8793"
      // How do I define this in the Pact JSON?
      widgets[0].Id.Should().NotBeEmpty();
...

Solution

  • My solution was to use the matchers in Pact.V4. In the WithJsonBody method, I defined the id as follows:

    id = PactNet.Matchers.Match.Type(Guid.NewGuid())
    

    This generated type validations in the JSON Pact file for the IDs.