Contract Testing Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Contract Testing runs in O(n) time and O(n) space, in C# as in every other language.
- ✓PactNet on NuGet (with PactNet.Output.Xunit for test output), another wrapper over the Rust core.
- ✓The mock must be driven by the same client you register in DI, configured with the same JsonSerializerOptions, or the contract proves nothing about production.
- ✓The C# trap: System.Text.Json is case-sensitive by default, unlike Newtonsoft.Json: a provider field named userId binds to null on a UserId property unless you set PropertyNameCaseInsensitive or a JsonNamingPolicy.
- ✓System.Text.Json reads UTF-8 bytes directly through Utf8JsonReader over a Span<byte>, so binding a mock response allocates about one object per node with no intermediate string for property names.
What Contract Testing actually is
Contract Testing in C#: what you actually reach for
C# implementation
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using PactNet;
using Xunit;
public class OrderClientTests
{
private readonly IPactBuilderV4 pact = Pact
.V4("web", "orders", new PactConfig { PactDir = "../../../pacts" })
.WithHttpInteractions();
[Fact]
public async Task FetchesAnOrder()
{
pact.UponReceiving("a request for order 42")
.Given("order 42 exists")
.WithRequest(HttpMethod.Get, "/orders/42")
.WithHeader("Accept", "application/json")
.WillRespond()
.WithStatus(HttpStatusCode.OK)
.WithJsonBody(new
{
id = Match.Type(42),
lines = Match.MinType(new { sku = Match.Type("ABC") }, 1)
});
// await, or the pact file is never written.
await pact.VerifyAsync(async ctx =>
{
// Same JsonSerializerOptions as the DI-registered client, or this
// proves nothing: System.Text.Json is case-sensitive by default.
var client = new OrderClient(ctx.MockServerUri,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
var order = await client.FetchAsync(42);
Assert.Equal(42, order.Id);
});
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Contract Testing?
PactNet on NuGet (with PactNet.Output.Xunit for test output), another wrapper over the Rust core. Consumer: var pact = Pact.V4("web", "orders", new PactConfig { PactDir = "../../../pacts" }).WithHttpInteractions(), then pact.UponReceiving(...).Given(...).WithRequest(HttpMethod.Get, "/orders/42").WillRespond().WithStatus(HttpStatusCode.OK).WithJsonBody(new { id = Match.Type(42) }), finished by await pact.VerifyAsync(async ctx => ...). Matchers are Match.Type, Match.MinType and Match.Regex. Provider: PactVerifier with .WithHttpEndpoint(uri), .WithPactBrokerSource(...), .WithProviderStateUrl(...) and .Verify().
What is the most common C# mistake when implementing Contract Testing?
System.Text.Json is case-sensitive by default, unlike Newtonsoft.Json: a provider field named userId binds to null on a UserId property unless you set PropertyNameCaseInsensitive or a JsonNamingPolicy. If the test deserialises with different options than your DI-registered HttpClient, the contract passes while production quietly returns nulls. Nullable reference types never save you there, because they are compile-time annotations only and the property simply holds null at runtime. And a struct DTO cannot be null but its fields take default values, so an omitted number becomes 0 rather than an error; use a class or record with required members (C# 11) so absence is visible.
How does Contract Testing actually perform in C#?
System.Text.Json reads UTF-8 bytes directly through Utf8JsonReader over a Span<byte>, so binding a mock response allocates about one object per node with no intermediate string for property names. Newtonsoft's JsonConvert.DeserializeObject<T> also streams, through JsonTextReader straight into the POCO, and builds no JToken tree unless you call JObject.Parse or target a JToken; its extra Gen0 pressure is char-based handling, transcoding to UTF-16 and allocating string and char buffers per token. Neither shows up against the per-builder mock server start, which is process-level work, so group interactions on one builder. On the provider side, ASP.NET Core host startup is paid once per test collection unless a WebApplicationFactory is shared across them. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.