SharpAssert.Runtime 1.1.0

dotnet add package SharpAssert.Runtime --version 1.1.0
                    
NuGet\Install-Package SharpAssert.Runtime -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SharpAssert.Runtime" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SharpAssert.Runtime" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="SharpAssert.Runtime" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add SharpAssert.Runtime --version 1.1.0
                    
#r "nuget: SharpAssert.Runtime, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package SharpAssert.Runtime@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=SharpAssert.Runtime&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=SharpAssert.Runtime&version=1.1.0
                    
Install as a Cake Tool

<p align="center"> <img src="https://raw.githubusercontent.com/yevhen/sharp.assert/refs/heads/main/logo.png" alt="SharpAssert logo"/> </p>

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:

  1. You write: Assert(x == y)
  2. MSBuild rewrites: global::SharpAssert.SharpInternal.Assert(() => x == y, "x == y", "file.cs", 42)
  3. Runtime analysis: Expression tree provides detailed failure diagnostics when assertions fail

Features

  • ๐Ÿ” Detailed Expression Analysis - See exactly why your assertions failed
  • ๐ŸŽฏ Exception Testing - Throws<T> and ThrowsAsync<T> with detailed exception diagnostics
  • ๐Ÿ”ค String Diffs - Character-level inline diffs for strings (powered by DiffPlex)
  • ๐Ÿ“Š Collection Comparison - First mismatch, missing/extra elements detection
  • ๐Ÿ”Ž Object Deep Diff - Property-level differences for objects/records (powered by Compare-Net-Objects)
  • ๐Ÿ”— LINQ Operations - Enhanced diagnostics for Contains/Any/All operations
  • โšก Async/Await Support - Full support for async assertions with value diagnostics
  • ๐Ÿ’ซ Dynamic Types - Dynamic objects support (Expando)

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

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

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"

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 */ }));

// Access exception properties
var ex = Throws<ArgumentNullException>(() => throw new ArgumentNullException("param"));
Assert(ex.Message.Contains("param"));

// Async version
Assert(await ThrowsAsync<InvalidOperationException>(() =>
    Task.Run(() => throw new InvalidOperationException())));

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]

Troubleshooting

Rewriting not working

  1. Verify SharpAssert package is installed (SharpAssert.Runtime comes automatically)
  2. Ensure using static SharpAssert.Sharp; import
  3. Clean and rebuild: dotnet clean && dotnet build

No detailed error messages

  1. Check build output contains: "SharpAssert: Rewriting X source files"
  2. Verify rewritten files exist in obj/Debug/net9.0/SharpRewritten/
  3. Ensure SharpInternal.Assert calls are being made (check generated code)
  4. 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

MIT License

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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
1.1.0 107 10/18/2025
1.0.6 176 8/13/2025
1.0.5 173 8/13/2025
1.0.4 173 8/13/2025
1.0.3 175 8/13/2025
1.0.0 181 8/13/2025