Select Page

An API compatibility policy becomes useful when it names a consumer behavior you can test. For a customer response, “the old client still compiles” is too weak: the client might deserialize a response and quietly lose the customer’s name. This tutorial builds a small C# regression check for that failure.

The example tests JSON response compatibility for one existing client. It runs as a .NET 10 console application using only the base class library; no web server or test framework is required. The fixture targets net10.0, enables nullable checks and treats compiler warnings as errors.

Write the compatibility promise first

For our sample service, version 1 promises that customer 7 is represented by an integer Id and the string Name, with the values 7 and Ada in this fixed test dataset. A response that still parses but changes those values fails the regression check. The equality checks below are assertions for this customer fixture, not validation rules for every customer.

Microsoft’s API design guidance explains that adding a field can preserve compatibility when existing clients ignore unfamiliar fields; removing or renaming fields can break them. It also describes keeping existing versioned URIs available with their original representation. Those ideas motivate this sample policy:

Example policy for a customer response
Change Decision for this service Evidence to require
Add a response field Keep v1 only after checking supported consumers Old consumer tests, including their serializer settings
Rename Name or change Id’s type Introduce a v2 representation and preserve v1 Separate response tests for each version
Change a field’s meaning Review as a possible breaking change Assertions about the value the consumer uses
Retire v1 Agree a migration and retirement date with consumers first An owner, a published migration notice and consumer migration evidence

This is an example team policy, including the retirement process, rather than a universal versioning standard. For illustration, the service could expose /v1/customers/7 and /v2/customers/7. Choosing those paths does not implement routing; the console test below exercises neither endpoint.

Test the old client against candidate responses

The client model deliberately keeps its existing property names. The console serializer matches property names case-sensitively by default, as documented in System.Text.Json deserialization behavior. The JSON uses matching capitalization throughout.

The tolerant options use the default behavior of ignoring unmapped JSON properties. The strict options reject them using JsonUnmappedMemberHandling.Disallow, available since .NET 8. Microsoft’s unmapped-member documentation describes this switch. Testing both consumers prevents an unconditional claim that adding a response field is safe.

Create a console project, replace its entire Program.cs with the complete program below, then run it:

dotnet new console --framework net10.0 --name CompatibilityChecks
cd CompatibilityChecks
# Replace Program.cs with the complete program below.
dotnet run
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

const string baseline = """{"Id":7,"Name":"Ada"}""";
const string added = """{"Id":7,"Name":"Ada","Region":"EU"}""";
const string renamed = """{"Id":7,"DisplayName":"Ada"}""";
const string changedType = """{"Id":"seven","Name":"Ada"}""";
const string changedValue = """{"Id":7,"Name":"Unknown"}""";

var tolerant = new JsonSerializerOptions();
var strict = new JsonSerializerOptions
{
    UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow
};

Check("baseline", baseline, tolerant, expected: true);
Check("added field / tolerant client", added, tolerant, expected: true);
Check("added field / strict client", added, strict, expected: false);
Check("renamed field", renamed, tolerant, expected: false);
Check("changed type", changedType, tolerant, expected: false);
Check("changed value", changedValue, tolerant, expected: false);

// Negative control: successful parsing alone misses the renamed field.
CustomerV1? parsed = JsonSerializer.Deserialize<CustomerV1>(renamed, tolerant);
if (parsed is null || parsed.Name is not null || PreservesCustomer(renamed, tolerant))
    throw new InvalidOperationException("Negative control did not expose the missing name.");
Console.WriteLine("PASS negative control: parsing succeeded but Name was lost");
Console.WriteLine("All 7 checks passed.");

static bool PreservesCustomer(string json, JsonSerializerOptions options)
{
    try
    {
        CustomerV1? customer = JsonSerializer.Deserialize<CustomerV1>(json, options);
        return customer is { Id: 7, Name: "Ada" };
    }
    catch (JsonException)
    {
        return false;
    }
}

static void Check(string label, string json, JsonSerializerOptions options, bool expected)
{
    bool actual = PreservesCustomer(json, options);
    if (actual != expected)
        throw new InvalidOperationException($"{label}: expected {expected}, got {actual}");
    Console.WriteLine($"PASS {label}: {(actual ? "compatible" : "incompatible")}");
}

public sealed class CustomerV1
{
    public int Id { get; set; }
    public string? Name { get; set; }
}

Expected standard output:

PASS baseline: compatible
PASS added field / tolerant client: compatible
PASS added field / strict client: incompatible
PASS renamed field: incompatible
PASS changed type: incompatible
PASS changed value: incompatible
PASS negative control: parsing succeeded but Name was lost
All 7 checks passed.

Read the failures as compatibility evidence

“Incompatible” is an expected result for the deliberately breaking payloads, so these checks pass when they detect the break. The changed-type case is rejected during deserialization. The renamed-field case is more subtle: the old Name property is left null, and the consumer assertion rejects the result. The final negative control explicitly confirms that this renamed payload still produces an object, exposing why a parse-only test would miss the loss.

The changed-value case keeps the same property names and JSON types but substitutes Unknown for Ada. It demonstrates that checking shape alone cannot protect this fixture’s expected value. It does not establish every business rule: add cases for units, status meanings and other behavior your actual clients depend on.

An unexpected result throws an exception instead of printing a passing line. For example, weakening PreservesCustomer to accept any non-null object would make the renamed-field check fail. All data is in memory; each invocation creates fresh options and objects, with no files, network calls, clock dependence or persistent state to clean up.

Use the check when deciding whether to version

Keep the old client model and its actual serializer configuration in your regression suite. Add candidate server responses as test data, and assert what the client does with them. When a supported consumer fails, preserve the old response and introduce a separate version for the incompatible representation, or revise the proposed change.

This program verifies one client’s deserialization and value expectations against fixed strings. It does not test production serialization, ASP.NET Core defaults, HTTP status codes, authentication, version selection, deployment compatibility or all possible clients. Before releasing a web API change, run integration checks against the real versioned endpoints and supported consumer configurations. A passing console check alone cannot approve that release.

For more on choosing assertions, see Design C# unit tests around observable behavior. If exception handling is unfamiliar, review C# Station’s introduction to exception handling before adapting the JsonException handling.

Share This