SharpAssert.Runtime
2.1.0
dotnet add package SharpAssert.Runtime --version 2.1.0
NuGet\Install-Package SharpAssert.Runtime -Version 2.1.0
<PackageReference Include="SharpAssert.Runtime" Version="2.1.0" />
<PackageVersion Include="SharpAssert.Runtime" Version="2.1.0" />
<PackageReference Include="SharpAssert.Runtime" />
paket add SharpAssert.Runtime --version 2.1.0
#r "nuget: SharpAssert.Runtime, 2.1.0"
#:package SharpAssert.Runtime@2.1.0
#addin nuget:?package=SharpAssert.Runtime&version=2.1.0
#tool nuget:?package=SharpAssert.Runtime&version=2.1.0
SharpAssert
A pytest inspired assertion library for .NET with no special syntax.
Overview
SharpAssert provides rich assertion diagnostics by automatically transforming your assertion expressions at compile time using MSBuild source rewriting, giving you detailed failure messages with powerful expression analysis.
using static SharpAssert.Sharp;
var items = new[] { 1, 2, 3 };
var target = 4;
Assert(items.Contains(target));
// Assertion failed: items.Contains(target) at MyTest.cs:15
// items: [1, 2, 3]
// target: 4
// Result: false
How It Works
SharpAssert uses MSBuild source rewriting to automatically transform your assertion calls at compile time:
- You write:
Assert(x == y) - MSBuild rewrites:
global::SharpAssert.SharpInternal.Assert(() => x == y, "x == y", "file.cs", 42) - Runtime analysis: Expression tree provides detailed failure diagnostics when assertions fail
Features
- Detailed Expression Analysis - See exactly why your assertions failed
- Native Short-Circuit Checks - Standard C# operators with focused failure diagnostics
- Exception Testing -
Throws<T>andThrowsAsync<T>with detailed exception diagnostics - String Diffs - Character-level inline diffs for strings (powered by DiffPlex)
- String Pattern Matching - Wildcard patterns and occurrence counting
- Collection Comparison - First mismatch, missing/extra elements detection
- Collection Ordering - Ascending/descending order validation
- Collection Uniqueness - Duplicate detection with key selectors
- Collection Quantifiers -
Each,Some,None,One,Exactlywith per-item diagnostics - Object Deep Diff - Property-level differences for objects/records (powered by Compare-Net-Objects)
- Object Equivalency - Structural comparison with property exclusion/inclusion
- LINQ Operations - Enhanced diagnostics for Contains/Any/All operations
- Async/Await Support - Full support for async assertions with value diagnostics
Live Examples
See demo for assertion example output.
Quick Start
1. Install Package
dotnet add package SharpAssert
2. Using SharpAssert
using static SharpAssert.Sharp;
[Test]
public void Should_be_equal()
{
var expected = 4;
var actual = 5;
Assert(expected == actual);
// Assertion failed: expected == actual
// Left: 4
// Right: 5
// Result: false
}
Features in Detail
Multiple Conditions
SharpAssert keeps C# short-circuit evaluation. && stops at the first false
condition. || stops at the first true condition. Each reached condition runs once,
and failure diagnostics do not run it again.
var x = 3;
var y = 7;
Assert(x == 5 && y == 10);
// Assertion failed: x == 5 && y == 10
// x == 5
// Left: 3
// Right: 5
The failure shows the condition that stopped an AND expression. A failed OR expression shows why each reached alternative failed. Diagnostics keep logical groups and do not report skipped conditions as false.
Null and type guards keep their C# behavior:
Assert(value != null && value.Id == 42);
Assert(value is ExpectedType { Id: 42 });
A compound assertion does not replace Assert.Multiple or an assertion scope.
Use an explicit multiple-assertion construct when all independent checks must run.
Enum comparisons show member names, including nullable enums and combined flags.
Explicit numeric casts such as (int)status still show numbers. Unnamed enum
values also remain numeric. Diagnostics do not read the operands again.
Property patterns use native C# matching, including nested properties, relational
patterns, and and/or patterns. A failed root pattern reports the source pattern
and the actual input type (or null). Diagnostics do not read the properties again.
Works with custom expectations too:
using SharpAssert.Features.Strings;
Assert("foo".Matches("oof") & "bar".Matches("rab"));
// Shows both pattern match failures with full diagnostics
String Comparisons
Character-level diffs powered by DiffPlex:
var actual = "hello";
var expected = "hallo";
Assert(actual == expected);
// Assertion failed: actual == expected
// String diff (inline):
// h[-e][+a]llo
Multiline string diffs:
var actual = "line1\nline2\nline3";
var expected = "line1\nMODIFIED\nline3";
Assert(actual == expected);
// Assertion failed: actual == expected
// String diff:
// line1
// - line2
// + MODIFIED
// line3
Collection Comparisons
First mismatch and missing/extra elements:
var actual = new[] { 1, 2, 3, 5 };
var expected = new[] { 1, 2, 4, 5 };
Assert(actual.SequenceEqual(expected));
// Assertion failed: actual.SequenceEqual(expected)
// Collections differ at index 2:
// Expected: 4
// Actual: 3
List the expected items inline, in order or in any order:
using SharpAssert.Features.Collections;
Assert(ids.IsSequence(1, 2, 3)); // same items, same order
Assert(ids.HasSameItems(3, 1, 2)); // same items, any order, duplicates counted
Assert(names.HasSameItems(expected, StringComparer.OrdinalIgnoreCase));
// Expected the same items as [3, 1, 2], but found [1, 2, 4]: missing [3], extra [4].
String Pattern Matching
Wildcard patterns with * (any sequence) and ? (single character):
using SharpAssert.Features.Strings;
Assert("hello world".Matches("hello *")); // * matches any sequence
Assert("test.txt".Matches("*.txt")); // File extension matching
Assert("test".Matches("t?st")); // ? matches single character
Assert("HELLO".MatchesIgnoringCase("hello")); // Case-insensitive
Count substring occurrences:
Assert("error at line 5, error at line 10".Contains("error", Occur.Exactly(2)));
Assert("warn, warn, warn".Contains("warn", Occur.AtLeast(2)));
Assert("info".Contains("info", Occur.AtMost(1)));
Regex pattern occurrence counting:
Assert("test123 and test456".MatchesRegex(@"test\d+", Occur.Exactly(2)));
Collection Ordering
Validate collections are sorted:
using SharpAssert.Features.Collections;
var ascending = new[] { 1, 2, 3, 4 };
Assert(ascending.IsInAscendingOrder());
var descending = new[] { 4, 3, 2, 1 };
Assert(descending.IsInDescendingOrder());
// With custom comparer
Assert(names.IsInAscendingOrder(StringComparer.OrdinalIgnoreCase));
Collection Uniqueness
Validate collections contain no duplicates:
using SharpAssert.Features.Collections;
var unique = new[] { 1, 2, 3, 4 };
Assert(unique.AllUnique());
// Uniqueness by property
var users = new[] { user1, user2, user3 };
Assert(users.AllUnique(u => u.Email));
// Custom equality comparer
Assert(items.AllUnique(StringComparer.OrdinalIgnoreCase));
Collection Quantifiers
Check how many items match a condition. Failures list the items that broke it:
using SharpAssert; // quantifiers are in SharpAssert, not SharpAssert.Features.Collections
Assert(orders.Each(o => o.Total > 0)); // every item; passes on an empty collection
Assert(orders.Some(o => o.IsPaid)); // at least one
Assert(orders.None(o => o.IsCancelled)); // no item
Assert(orders.One(o => o.IsDraft)); // exactly one
Assert(orders.Exactly(2, o => o.IsUrgent)); // also AtLeast and AtMost
Each passes on an empty collection, like LINQ All. Add Assert(orders.Any()) when
the collection must not be empty.
Object Deep Comparison
Property-level diffs powered by Compare-Net-Objects:
var actual = new User { Name = "John", Age = 30, City = "NYC" };
var expected = new User { Name = "John", Age = 25, City = "LA" };
Assert(actual == expected);
// Assertion failed: actual == expected
// Object differences:
// Age: 30 → 25
// City: "NYC" → "LA"
Object Equivalency
Structural comparison with fluent configuration:
var actual = new Person { Name = "John", Age = 30, Id = 1 };
var expected = new Person { Name = "John", Age = 30, Id = 2 };
// Basic equivalency check
Assert(actual.IsEquivalentTo(expected));
// Exclude specific properties
Assert(actual.IsEquivalentTo(expected, config => config.Excluding(p => p.Id)));
// Include only specific properties
Assert(actual.IsEquivalentTo(expected, config => config.Including(p => p.Name)));
// Ignore collection ordering
var team1 = new Team { Members = new[] { "Alice", "Bob" } };
var team2 = new Team { Members = new[] { "Bob", "Alice" } };
Assert(team1.IsEquivalentTo(team2, config => config.WithoutStrictOrdering()));
DateTimeOffset values compare by instant, including tick precision; offsets can
differ. To compare offsets too, use an explicit comparer:
Assert(actual.IsEquivalentTo(expected, config =>
config.Using<DateTimeOffset>((left, right) => left.EqualsExact(right))));
LINQ Operations
Enhanced diagnostics for Contains, Any, All:
var users = new[] { "Alice", "Bob", "Charlie" };
Assert(users.Contains("David"));
// Assertion failed: users.Contains("David")
// Collection: ["Alice", "Bob", "Charlie"]
// Looking for: "David"
// Result: false
Async/Await Support
Full support for async expressions:
Assert(await client.GetAsync() == await server.GetAsync());
// Assertion failed: await client.GetAsync() == await server.GetAsync()
// Left: { Id: 1, Name: "Client" }
// Right: { Id: 2, Name: "Server" }
// Result: false
Exception Testing
Test expected exceptions with Throws<T> and ThrowsAsync<T>:
// Positive assertion - expects exception
Assert(Throws<ArgumentException>(() => throw new ArgumentException("invalid")));
// Negative assertion - expects no exception
Assert(!Throws<ArgumentException>(() => { /* no exception */ }));
// Read exception properties inside the assertion.
Assert(Throws<ArgumentNullException>(() => throw new ArgumentNullException("param")).Message.Contains("param"));
// Check one captured message without running the action again.
Assert(Throws<InvalidOperationException>(() => Validate()).Message is var message
&& message.Contains("region")
&& message.Contains("country"));
// Async version
Assert(await ThrowsAsync<InvalidOperationException>(() =>
Task.Run(() => throw new InvalidOperationException())));
Throws<T> also accepts subclasses of T. To require the exact type, check it with
IsExactly<T>(), which works on any value:
Assert(Throws<ArgumentException>(() => Parse(text)).Exception.IsExactly<ArgumentException>());
Assert(chart.IsExactly<TextChart>());
// Expected type TextChart, but found ImageChart.
Keep single-use delegates and exception checks inside Assert. Do not add an
Action variable and a separate result just to assert one property. Compound
conditions on one captured exception are valid; the action runs once.
Custom Expectations
Create reusable expectations using Expectation.From() - a lambda-based factory that eliminates boilerplate:
public static class NumberExtensions
{
public static Expectation IsEven(this int value) =>
Expectation.From(
() => value % 2 == 0,
() => [$"Expected even number, got {value}"]
);
public static Expectation IsBetween(this int value, int min, int max) =>
Expectation.From(
() => value >= min && value <= max,
() => [$"Expected {value} to be between {min} and {max}"]
);
}
Assert(4.IsEven());
Assert(!5.IsEven());
Assert(5.IsBetween(1, 10));
How it works:
- First lambda: predicate that returns
trueif expectation passes - Second lambda: failure message factory (only called on failure, returns
string[]for multiple diagnostic lines) - Expression text is injected automatically by the framework
For complex expectations with substantial internal logic (algorithms, external library integration), you can still inherit from Expectation:
sealed class IsEquivalentToExpectation<T>(T actual, T expected) : Expectation
{
public override EvaluationResult Evaluate(ExpectationContext context)
{
// Complex comparison logic using Compare-Net-Objects...
return isEqual
? ExpectationResults.Pass(context.Expression)
: ExpectationResults.Fail(context.Expression, differences);
}
}
Custom Error Messages
Assert(user.IsActive, $"User {user.Name} should be active for this operation");
Complex Expression Analysis
var order = new Order { Items = new[] { "Coffee", "Tea" }, Total = 15.50m };
var expectedTotal = 12.00m;
Assert(order.Items.Length > 0 && order.Total == expectedTotal);
// Assertion failed: order.Items.Length > 0 && order.Total == expectedTotal
// order.Items.Length > 0 → True (Length: 2)
// order.Total == expectedTotal → False
// order.Total: 15.50
// expectedTotal: 12.00
// Result: False
Architecture
SharpAssert is built on modern .NET technologies:
- MSBuild Source Rewriting - Compile-time code transformation
- Roslyn Syntax Analysis - Advanced C# code parsing and generation
- Expression Trees - Runtime expression analysis for rich diagnostics
- DiffPlex - String and sequence diffs
- CompareNETObjects - Deep object comparison
- CallerArgumentExpression - Fallback for edge cases
Requirements
- .NET 9.0 or later
- Test frameworks: xUnit, NUnit, or MSTest
Packages
SharpAssert consists of two NuGet packages:
- SharpAssert - Main package with MSBuild rewriter (install this one)
- SharpAssert.Runtime - Core assertion library (automatically included as dependency)
When you install SharpAssert, you get everything you need. The runtime package is a transitive dependency and requires no separate installation.
Configuration
Diagnostic Logging
Enable detailed rewriter diagnostics:
<PropertyGroup>
<SharpAssertEmitRewriteInfo>true</SharpAssertEmitRewriteInfo>
</PropertyGroup>
Performance
SharpAssert is designed for minimal overhead:
- Passing tests: Near-zero overhead - only the assertion check itself
- Failing tests: Rich diagnostics are computed only when assertions fail
- Expression evaluation: Each sub-expression evaluated exactly once (cached)
- Build time: Negligible impact - rewriter processes only test files
The rich diagnostic tools (object diffing, collection comparison) are only invoked on failure. This means your passing tests run at full speed, and the diagnostic cost is only paid when you need to understand a failure.
Known Issues
- Collection initializers cannot be used in expression trees (C# compiler limitation)
- Use
new[]{1,2,3}instead of[1, 2, 3]
- Use
Troubleshooting
Rewriting not working
- Verify
SharpAssertpackage is installed (SharpAssert.Runtime comes automatically) - Ensure
using static SharpAssert.Sharp;import - Clean and rebuild:
dotnet clean && dotnet build
No detailed error messages
- Check build output contains: "SharpAssert: Rewriting X source files"
- Verify rewritten files exist in
obj/Debug/net9.0/SharpRewritten/ - Ensure
SharpInternal.Assertcalls are being made (check generated code) - Look for #line directives in generated files
Enable diagnostic logging
For troubleshooting rewriter issues:
<PropertyGroup>
<SharpAssertEmitRewriteInfo>true</SharpAssertEmitRewriteInfo>
</PropertyGroup>
Then rebuild with verbose output: dotnet build -v detailed
Contributing
We welcome contributions! Please see our comprehensive Contributing Guide for:
- Quick start guide for developers
- Testing strategy and workflow
- Package versioning best practices
- Development tips and debugging help
- Commit guidelines and release process
License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. 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. |
-
net9.0
- DiffPlex (>= 1.8.0)
- SharpAssert.CompareNETObjects (>= 4.84.0-sharpassert.1)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on SharpAssert.Runtime:
| Package | Downloads |
|---|---|
|
SharpAssert
A pytest inspired assertion library for .NET with no special syntax. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 2.1.0 | 0 | 12/3/2026 |
| 2.0.0 | 5,977 | 10/29/2026 |
| 1.6.1 | 99 | 10/9/2026 |
| 1.6.0 | 98 | 10/1/2026 |
| 1.5.1 | 4,136 | 10/1/2026 |
| 1.5.0 | 137 | 9/26/2026 |
| 1.4.1 | 1,683 | 1/28/2026 |
| 1.4.0 | 352 | 12/18/2025 |
| 1.3.0 | 4,526 | 12/16/2025 |
| 1.2.0 | 385 | 12/15/2025 |
| 1.1.0 | 641 | 10/18/2025 |
| 1.0.6 | 290 | 8/13/2025 |
| 1.0.5 | 268 | 8/13/2025 |
| 1.0.4 | 261 | 8/13/2025 |
| 1.0.3 | 264 | 8/13/2025 |
| 1.0.0 | 280 | 8/13/2025 |
Add IsSequence, HasSameItems and IsExactly. Fix WithoutStrictOrdering to compare every item, awaited comparisons of numbers of different types, ulong comparisons with constants, asserts inside #if blocks that were not rewritten, and builds that compiled sources without the rewrite. A build without changes does not compile again.