Lesson 27 of 93 · 8 min read · Updated

Property-Based Testing in .NET: From a Hand-Written Loop to FsCheck and CsCheck

Example-based tests check the inputs you thought of. Property-based tests state a rule that must hold for every valid input and let a generator try hundreds of inputs you did not think of. This lesson builds the idea in three steps: first a hand-written version with a loop and a fixed seed, so the mechanism is clear, then the same properties with FsCheck and with CsCheck. Along the way you will see the two features that make a library worth adding: shrinking and replay.

Technical Requirements

  1. .NET 11 SDK
  2. xunit 2.9.3
  3. xunit.runner.visualstudio 4.0.1 and Microsoft.NET.Test.Sdk 18.12.0
  4. FsCheck.Xunit 3.6.0 (BSD-3-Clause licence)
  5. CsCheck 5.0.1 (Apache-2.0 licence)

The Code Under Test: a Roman Numeral Converter

A converter between integers and Roman numerals is a good candidate for property-based testing. The valid input space is clear (1 to 3999), and there is a rule that must hold for all of it: converting a number to a Roman numeral and back gives the original number.

M03.DataDriven/RomanNumeral.cs

public static class RomanNumeral
{
private static readonly (int Value, string Symbol)[] Map =
[
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"),
];

/// <summary>Converts a number in the range 1..3999 to a Roman numeral.</summary>
public static string ToRoman(int value)
{
if (value is < 1 or > 3999)
{
throw new ArgumentOutOfRangeException(
nameof(value), value, "Roman numerals only support the range 1..3999.");
}

var result = new System.Text.StringBuilder();
foreach (var (amount, symbol) in Map)
{
while (value >= amount)
{
result.Append(symbol);
value -= amount;
}
}

return result.ToString();
}

/// <summary>Converts a Roman numeral to a number.</summary>
public static int Parse(string roman)
{
ArgumentException.ThrowIfNullOrWhiteSpace(roman);

var index = 0;
var total = 0;

foreach (var (amount, symbol) in Map)
{
while (index + symbol.Length <= roman.Length &&
roman.AsSpan(index, symbol.Length).SequenceEqual(symbol))
{
total += amount;
index += symbol.Length;
}
}

if (index != roman.Length)
{
throw new FormatException($"Invalid Roman numeral: '{roman}'.");
}

return total;
}
}

Step 1: Properties by Hand

A property is an invariant: a statement that is true for every valid input. The hand-written version below checks three of them with plain xUnit and no extra packages.

M03.DataDriven.Tests/PropertyBasedTests.cs

public class PropertyBasedTests
{
private const int Seed = 20260314;

[Fact]
public void ToRomanThenParse_IsRoundTripForEveryValidNumber()
{
// Invariant #1: the round trip is lossless.
// We can scan the whole valid space (1..3999), so we do a FULL scan here.
foreach (var value in Enumerable.Range(1, 3_999))
{
var roman = RomanNumeral.ToRoman(value);
Assert.Equal(value, RomanNumeral.Parse(roman));
}
}

[Fact]
public void ToRoman_PreservesOrdering()
{
// Invariant #2: if a < b, the numeric value of ToRoman(a) is always less than that of ToRoman(b).
var random = new Random(Seed);

for (var i = 0; i < 500; i++)
{
var a = random.Next(1, 4_000);
var b = random.Next(1, 4_000);

var comparison = RomanNumeral.Parse(RomanNumeral.ToRoman(a))
.CompareTo(RomanNumeral.Parse(RomanNumeral.ToRoman(b)));

Assert.Equal(Math.Sign(a.CompareTo(b)), Math.Sign(comparison));
}
}

[Fact]
public void ToRoman_OnlyUsesValidSymbols()
{
// Invariant #3: the output contains only valid symbols.
var random = new Random(Seed);

for (var i = 0; i < 500; i++)
{
var roman = RomanNumeral.ToRoman(random.Next(1, 4_000));
Assert.Matches("^[MDCLXVI]+$", roman);
}
}

[Theory]
[InlineData(0)]
[InlineData(4_000)]
[InlineData(-5)]
public void ToRoman_OutsideSupportedRange_Throws(int value)
{
// Property tests guard broad rules; test the BOUNDARIES with examples.
Assert.Throws<ArgumentOutOfRangeException>(() => RomanNumeral.ToRoman(value));
}
}

The first test does not sample at all. The input space has only 3999 values, so it checks every one of them. When the space is that small, a full scan is the strongest test you can write.

The other two tests sample 500 random values. The important detail is the fixed seed: new Random(Seed) produces the same sequence on every run. Without a seed, the test could pass today and fail tomorrow on a value you can never reproduce. With a seed, a failure happens again on the next run, and you can debug it.

The last test is a theory with examples, not a property. Properties guard broad rules over the valid space. The exact edges, such as 0 and 4000, are better pinned with explicit examples.

The hand-written version has two weaknesses. When it fails, it reports whatever random value broke the rule, which may be large and hard to reason about. And every generator is a hand-written loop. A library solves both.

Step 2: The Same Properties with FsCheck

FsCheck is a property-based testing library for .NET. The FsCheck.Xunit package adds a [Property] attribute that runs a property as an xUnit test.

M03.DataDriven.Tests/FsCheckPropertyTests.cs

public class FsCheckPropertyTests
{
/// <summary>The space of valid Roman numerals: 1..3999.</summary>
private static Arbitrary<int> ValidRomanRange() => Gen.Choose(1, 3_999).ToArbitrary();

[Property(MaxTest = 500)]
public Property ToRomanThenParse_IsRoundTrip() =>
// Invariant: Parse(ToRoman(n)) == n. FsCheck tries 500 different values of n.
Prop.ForAll(ValidRomanRange(), n => RomanNumeral.Parse(RomanNumeral.ToRoman(n)) == n);

[Property(MaxTest = 500)]
public Property ToRoman_OnlyUsesValidSymbols() =>
Prop.ForAll(ValidRomanRange(), n => RomanNumeral.ToRoman(n).All(c => "MDCLXVI".Contains(c)));
}

Gen.Choose(1, 3_999) is a generator of integers in that closed range. ToArbitrary() wraps it in an Arbitrary<int>, which FsCheck uses to produce values. Prop.ForAll combines the arbitrary with a predicate, and MaxTest = 500 sets how many inputs FsCheck tries. The code uses the C# API from the FsCheck.Fluent namespace.

When a property fails, FsCheck prints the failing input and a Replay value. Put that value into [Property(Replay = "...")], and FsCheck runs the exact same sequence again, which plays the role of the fixed seed in the hand-written version.

Shrinking: Finding the Smallest Counterexample

The most useful feature of a property-based library is shrinking. When FsCheck finds a failing input, it tries smaller inputs until it finds the smallest one that still fails. The test below shows this with a property that is wrong on purpose.

M03.DataDriven.Tests/FsCheckPropertyTests.cs

[Fact]
public void WrongProperty_IsShrunkToMinimalCounterexample()
{
// An intentionally WRONG property: "for every n, n < 100".
// FsCheck first finds a large random counterexample (for example 523),
// then shrinks it step by step and reports the EXACT boundary: 100.
//
// CAREFUL: Gen.Choose(...).ToArbitrary() on its own has NO shrinker.
// For shrinking, we pass the generator together with the default int shrinker.
var intShrinker = ArbMap.Default.ArbFor<int>();
var arbitrary = Arb.From(Gen.Choose(0, 1_000), n => intShrinker.Shrinker(n));
var wrongProperty = Prop.ForAll(arbitrary, (int n) => n < 100);

var exception = Assert.ThrowsAny<Exception>(
() => Check.One(Config.QuickThrowOnFailure, wrongProperty));

// The failure message contains both the original and the shrunk example.
Assert.Contains("Shrunk", exception.Message);
Assert.Matches(@"Shrunk:\s*100\b", exception.Message);
}

The claim "every n is less than 100" is false. FsCheck finds some value such as 523, then shrinks it toward zero. It stops at 100, because 99 passes and 100 fails. The report shows 100, which points straight at the boundary. A random 523 would tell you only that something is wrong somewhere above 100.

Check.One(Config.QuickThrowOnFailure, ...) runs the property inside a normal test and throws on failure. The test catches that exception and asserts that the message contains the shrunk value.

Pitfall: Gen.Choose(...).ToArbitrary() does not include a shrinker. A property built on it reports the original random failure, not the minimal one. If you want shrinking with a custom generator, pass a shrinker explicitly with Arb.From(gen, shrinker), as the test does with the default integer shrinker from ArbMap.Default.ArbFor<int>().

Step 3: The Same Idea with CsCheck

CsCheck is a property-based testing library written for C#. It does not depend on any test framework. There is no special attribute: you call Sample inside an ordinary [Fact].

M03.DataDriven.Tests/CsCheckPropertyTests.cs

public class CsCheckPropertyTests
{
[Fact]
public void ToRomanThenParse_IsRoundTrip()
{
// Gen.Int[1, 3999]: an integer generator over a closed range.
Gen.Int[1, 3_999].Sample(
n => RomanNumeral.Parse(RomanNumeral.ToRoman(n)) == n,
iter: 500);
}

[Fact]
public void ToRoman_PreservesOrdering()
{
// We combine two independent generators to produce (a, b) pairs.
Gen.Select(Gen.Int[1, 3_999], Gen.Int[1, 3_999]).Sample(
(a, b) => Math.Sign(a.CompareTo(b)) ==
Math.Sign(RomanNumeral.Parse(RomanNumeral.ToRoman(a))
.CompareTo(RomanNumeral.Parse(RomanNumeral.ToRoman(b)))),
iter: 500);
}
}

Gen.Int[1, 3_999] is CsCheck's integer generator for a closed range. Sample runs the predicate for iter generated values. If the predicate returns false or throws, Sample throws an exception whose message contains the shrunk input and a seed. Passing that seed back with Sample(..., seed: "...") replays the same run exactly.

Gen.Select combines two generators into one that produces pairs. This is how you build inputs for properties over several values, such as the ordering rule.

Choosing an Approach

ApproachGood for
Full scan with a loopSmall input spaces, like 1 to 3999
Hand-written loop with a fixed seedLearning the idea, or when no extra package is allowed
FsCheck with [Property]Rich generators, shrinking, Replay values
CsCheck with SampleC#-first API, framework independent, seed replay

The rule stays the same in every version: test broad rules with properties, and test known boundaries with examples.

Summary

  1. A property is an invariant that must hold for every valid input, such as Parse(ToRoman(n)) == n.
  2. When the input space is small, scan all of it; when it is large, sample it with a fixed seed so failures are reproducible.
  3. FsCheck and CsCheck add generators, shrinking to the smallest counterexample, and replay through Replay or seed values.
  4. In FsCheck, Gen.Choose(...).ToArbitrary() has no shrinker; use Arb.From(gen, shrinker) when you need one.
  5. Combine properties for broad rules with example-based tests for exact boundaries.