Pact: Mixed topics


Pact.NET related topics

Consumer unit test

Example of a GET API call with parameters

[Fact]
public async void GetProductsBySomeParams_WithValidParameters()
{
	var expectedResponse = new[] {
		new {
			id = Match.Type("e0eb64df-8d91-48c7-a670-b972f85f94ca"),
			title = Match.Type("product-x"),
			description = Match.Type("Product-X is a smart device that learns your preferences and helps you be more productive and efficient in your daily tasks, with personalized recommendations and reminders. It's easy to use and perfect for busy professionals and families."),
		},
		new {
			id = Match.Type("12a97674-9514-4d0c-a756-65b4963ab383"),
			title = Match.Type("product-y"),
			description = Match.Type("Product-Y is a sleek and innovative tool that helps unleash your creativity and explore new ideas, with versatile features and an easy-to-use interface. It's perfect for artists, writers, entrepreneurs, and anyone looking to bring their visions to life."),
		}
	};

	var param1 = "xyz";
	var param2 = 2;

	pact.UponReceiving("a request to get users of a specific role and tenant with valid parameters")
		.WithRequest(HttpMethod.Get, $"/v1/Product/BySomeParams")
		.WithQuery("param1", param1)
		.WithQuery("param2", $"{param2}")
		.WithHeader("authorization", "Bearer SomeToken")
		.WithHeader("host", "127.0.0.1:6000")
		.WillRespond()
		.WithStatus(HttpStatusCode.OK)
		.WithHeader("Content-Type", "application/json; charset=utf-8")
		.WithJsonBody(expectedResponse);

	//Act
	await pact.VerifyAsync(async ctx =>
	{
		var someClient = new SomeClient();
		var result = await someClient.GetProductsBySomeParams(param1, param2);

		//Assert
		Assert.True(result.IsSuccessful);
	});
}

If you are developing a Pact unit test and your pact.VerfiyAsync() method throws an exception and cannot figure out why you might activate the mock provider debugging logs (see Enabling the mock provider debugging logs)

Having more verbose logs in the consumer test

The following code example shows how you can increase the log level of the consumer unit test and make it more verbose:

var config = new PactConfig
{
	PactDir = @$"{Directory.GetCurrentDirectory()}../../../pacts",
	LogLevel = PactLogLevel.Trace,
	Outputters = (new[]
	{
		new XUnitOutput(output)
	}),
	DefaultJsonSettings = new JsonSerializerSettings
	{
		ContractResolver = new CamelCasePropertyNamesContractResolver()
	}
};

Mock provider

Mock provider debugging logs

If you are developing a Pact.NET consumer unit test it might be quite useful to enable the mock provider debugging logs. You can achieve this by the –environment and –logger options of the "dotnet test" command:

dotnet test ./PactConsumerTest.csproj --environment "PACT_LOG_LEVEL=DEBUG" --configuration Release --logger "trx;LogFileName=pact_test_results.xml"

Pact, the two files Startup.cs & Program.cs and NET 6.0

Pact provider tests usually rely on the two files Startup.cs and Program.cs, which are still supported but not recommended in NET 6.0. The new recommended approach in NET 6.0 is to only use the Program.cs file, but as of 2022-11-10 all available examples of Pact.NET were based on the .NET applications having both Startup.cs and Program.cs. This might have changed in newer versions of Pact.NET.

As of 2022-11-10 some of the Pact.NET examples made use of a TestStatus.cs file instead of the default Startup.cs file provided by NET. The reason for that is that in the case of integration tests, it is a common approach to use custom startup classes instead of the normal startup class provided by .NET, this was the case at least before the introduction of the new model which only involves Program.cs.

Related topics

Pact.NET: Bi-Directional CT & DevOps Pipelines

Pact: bi-directional contract testing

Pact: Bi-Directional .NET example