Lesson 27 of 93 · 8 min read · Updated
Property-Based Testing in .NET: From a Hand-Written Loop to FsCheck and CsCheck
On this page
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
- .NET 11 SDK
- xunit 2.9.3
- xunit.runner.visualstudio 4.0.1 and Microsoft.NET.Test.Sdk 18.12.0
- FsCheck.Xunit 3.6.0 (BSD-3-Clause licence)
- 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
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
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
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
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
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
| Approach | Good for |
|---|---|
| Full scan with a loop | Small input spaces, like 1 to 3999 |
| Hand-written loop with a fixed seed | Learning the idea, or when no extra package is allowed |
FsCheck with [Property] | Rich generators, shrinking, Replay values |
CsCheck with Sample | C#-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
- A property is an invariant that must hold for every valid input, such as
Parse(ToRoman(n)) == n. - When the input space is small, scan all of it; when it is large, sample it with a fixed seed so failures are reproducible.
- FsCheck and CsCheck add generators, shrinking to the smallest counterexample, and replay through
Replayorseedvalues. - In FsCheck,
Gen.Choose(...).ToArbitrary()has no shrinker; useArb.From(gen, shrinker)when you need one. - Combine properties for broad rules with example-based tests for exact boundaries.