FluentContracts 4.0.1
Prefix Reserveddotnet add package FluentContracts --version 4.0.1
NuGet\Install-Package FluentContracts -Version 4.0.1
<PackageReference Include="FluentContracts" Version="4.0.1" />
<PackageVersion Include="FluentContracts" Version="4.0.1" />
<PackageReference Include="FluentContracts" />
paket add FluentContracts --version 4.0.1
#r "nuget: FluentContracts, 4.0.1"
#:package FluentContracts@4.0.1
#addin nuget:?package=FluentContracts&version=4.0.1
#tool nuget:?package=FluentContracts&version=4.0.1
FluentContracts
Argument validation that reads like the rule it enforces, and fails with a message that says what was expected of which argument.
dotnet add package FluentContracts
A guard clause, before and after
public void AddOrder(Order myOrder)
{
if (myOrder == null) throw new ArgumentNullException(nameof(myOrder));
if (myOrder.Quantity < 5) throw new ArgumentOutOfRangeException(nameof(myOrder), "Quantity cannot be less than 5");
}
public void AddOrder(Order myOrder)
{
myOrder.Must().NotBeNull().Satisfy<Order>(o => o.Quantity >= 5, "Quantity cannot be less than 5");
}
Must() starts a chain on any value. Every check returns the same chain, so checks follow one
another with no glue; .And. between them is optional and purely for reading. The argument's name
is captured at the call site, so exceptions point at the right parameter without nameof.
What every check gives you
A failure message that names the argument, the expectation and the value.
port.Must().BeBetween(1, 65535);
// ArgumentOutOfRangeException: Expected port to be between 1 and 65535, but found 70000. (Parameter 'port')
email.Must().BeEmailAddress();
// ArgumentException: Expected email to be a valid email address, but found "not-an-email". (Parameter 'email')
pages.Must().BeInAscendingOrder();
// ArgumentException: Expected pages to be in ascending order, but 5 appears before 3. (Parameter 'pages')
Your own message when you want one. It is always the last parameter, it replaces the default, and
it may use {argument} and {value}:
port.Must().BeBetween(1, 65535, "{argument} must be a usable port, got {value}");
// ArgumentOutOfRangeException: port must be a usable port, got 70000 (Parameter 'port')
environment.Must("This should be prod").NotBe("test").NotBeEmpty();
// one message for every check in the chain; a check's own message still wins
The validated value back, so the guard and the read are one expression:
this.port = config.Port.Must().BeBetween(1, 65535).Value();
Value() unwraps a nullable and fails a null argument exactly as NotBeNull would.
The right exception type, without choosing it:
| Failure | Throws |
|---|---|
a null argument |
ArgumentNullException |
| a comparison, range, sign or NaN check | ArgumentOutOfRangeException |
| everything else — equality, format, containment, type, your own rules | ArgumentException |
Or the exception you name: myOrder.Must().NotBeNull<OrderNullException>() and
Satisfy<Order, OrderQuantityException>(o => o.Quantity >= 5, "...") throw yours.
Frames you can read. The library hides its own frames from the stack trace, so a failure points at the check you wrote.
What you can check
Every type gets BeNull/NotBeNull, Be/NotBe, BeAnyOf/NotBeAnyOf and Satisfy; then
each adds what makes sense for it. The full list is in
SupportedContracts.md.
Numbers — int, long, short, byte, their unsigned forms, float, double, decimal, and
on .NET 8+ any INumber<T> such as Half, Int128 or BigInteger:
quantity.Must().BePositive().BeLessOrEqualTo(100);
retries.Must().BeBetween(1, 5);
page.Must().BeEven();
ratio.Must().BeFinite(); // neither NaN nor infinity
A comparison never passes on NaN and never passes on null; BeNaN and BeFinite are how you
ask about NaN on purpose.
Text and characters — shape, format and content:
name.Must().NotBeNullOrWhiteSpace().HaveLengthLessOrEqualTo(64);
code.Must().BeAlphanumeric().BeUppercase();
input.Must().BeEmailAddress(); // also BeUrl, BeIpAddress, BeGuid, BeBase64, BeHexadecimal, BeCreditCardNumber
path.Must().BeExistingFile();
slug.Must().BeMatching("^[a-z0-9-]+$");
title.Must().Contain("draft", StringComparison.OrdinalIgnoreCase); // Ordinal by default
initial.Must().BeLetter().BeUppercase();
Dates and times — DateTime, DateTimeOffset, TimeSpan, and on .NET 8+ DateOnly and
TimeOnly:
start.Must().BeInTheFuture().BeWeekday();
deadline.Must().BeBetween(start, end);
timeout.Must().BeLongerThan(TimeSpan.FromSeconds(1));
stamp.Must().BeUtc();
booking.Must().BeInCurrentYear().NotBeInDecember();
Checks that need the current time take a clock, so tests can pin it:
start.Must(dateTimeProvider: clock).BeInTheFuture().
Collections and dictionaries — arrays, IList<T>, IDictionary<TKey, TValue>:
items.Must().NotBeEmpty().HaveCountLessOrEqualTo(100).HaveUniqueItems();
tags.Must().Contain("public").NotContainNull();
scores.Must().BeInDescendingOrder().AllSatisfy(s => s >= 0);
settings.Must().ContainKey("region").NotContainKey("legacy");
BeAnyOf, Contain and ContainAnyOf take one value or one bracketed set:
state.Must().BeAnyOf(["draft", "published"], "Not a known state").
Enums, GUIDs, booleans:
role.Must().BeDefined().NotBe(Role.Guest);
flags.Must().HaveFlag(Permissions.Read);
id.Must().NotBeEmpty();
enabled.Must().BeTrue();
Files, directories, streams and URIs:
file.Must().Exist().NotBeEmpty().HaveExtension(".json").HaveSizeLessThan(1_000_000);
folder.Must().Exist().NotBeReadOnly();
stream.Must().BeReadable().BeSeekable();
endpoint.Must().BeAbsolute().BeHttps().HaveHost("api.example.com");
Any object — null, type, and a rule of your own:
payload.Must().NotBeNull().BeOfType<OrderPlaced>();
handler.Must().BeAssignableTo<IHandler>();
myOrder.Must().Satisfy<Order>(o => o.Quantity >= 5);
Your own rules
A rule you check in more than one place is a specification: a predicate and the phrase that
completes "Expected {argument} to …". Its failure reads exactly like a built-in check:
static readonly ISpecification<string> ValidIban =
Spec.From<string>(s => Iban.IsValid(s), "be a valid IBAN");
iban.Must().Satisfy(ValidIban);
// ArgumentException: Expected iban to be a valid IBAN, but found "XX00". (Parameter 'iban')
Rules compose — ValidIban.And(SepaCountry) expects "be a valid IBAN and be in a SEPA country",
ValidIban.Not() expects "not be a valid IBAN" — and a rule that needs more room than a lambda
derives from Specification<T> and overrides IsSatisfiedBy.
A type of your own can get a contract of its own: derive from ObjectContract<T, TContract>, add
checks that return the contract, and add a Must() extension for the type. Every check above then
chains with yours.
The package
- Targets
netstandard2.0andnet8.0: .NET Framework 4.6.1+, .NET Core, .NET 5 and later, Mono, Unity. - No runtime dependencies.
- Trimming and Native AOT compatible on
net8.0, verified on a trimmed and an AOT-published app. - A chain is one small object, and on .NET 10 the JIT keeps it off the heap entirely; see Benchmarks.md.
- Ships a Roslyn analyzer for the misuses that compile but check the wrong thing (none open at the moment).
Links
License
MIT © Todor Todorov
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- No dependencies.
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 4.0.1 | 129 | 9/4/2026 |
| 4.0.0 | 114 | 9/2/2026 |
| 3.7.0 | 112 | 9/2/2026 |
| 3.6.1 | 109 | 9/1/2026 |
| 3.6.0 | 124 | 9/1/2026 |
| 3.5.0 | 109 | 9/1/2026 |
| 3.4.0 | 116 | 9/1/2026 |
| 3.3.0 | 114 | 9/1/2026 |
| 3.2.0 | 135 | 8/31/2026 |
| 3.1.0 | 116 | 8/31/2026 |
| 3.0.0 | 121 | 8/30/2026 |
| 2.1.0 | 316 | 8/23/2024 |
| 2.0.0 | 266 | 6/16/2024 |
| 1.4.0 | 213 | 5/20/2024 |
| 1.3.0 | 256 | 5/6/2024 |
| 1.2.0 | 226 | 4/29/2024 |
| 1.1.1 | 241 | 4/26/2024 |
| 1.0.1 | 227 | 4/23/2024 |