Lesson 12 of 93 · 6 min read · Updated

Core xUnit Assertions: Equal, Same, Null, Single, All, Collection and Equivalent

xUnit ships with a set of assertions for values, booleans, nulls, references and collections. Most of them could be replaced with Assert.True(...) and a boolean expression, and that is exactly the mistake to avoid. This lesson walks through the core assertions and the one rule that ties them together: pick the narrowest assertion that explains the failure best.

Technical Requirements

  1. .NET 11 SDK
  2. xunit 2.9.3 (with xunit.runner.visualstudio and Microsoft.NET.Test.Sdk)

The Rule: Choose the Narrowest Assertion

Consider a check that a list has one element. Assert.True(list.Count == 1) works, but when it fails, the message is only "Expected: True, Actual: False". You have to rerun the test in a debugger to learn what the list held. Assert.Single(list) checks the same thing, and when it fails, xUnit reports how many elements the collection had and prints them. A specific assertion turns a red test into a diagnosis.

The examples use Product from earlier lessons and a small Catalog class:

M02.XUnitBasics/Catalog.cs

namespace M02.XUnitBasics;

public sealed class Catalog
{
private readonly Dictionary<string, Product> _products = [];

public void Add(Product product)
{
ArgumentNullException.ThrowIfNull(product);
_products[product.Sku] = product;
}

/// <summary>Returns null when not found (Assert.Null / Assert.NotNull example).</summary>
public Product? Find(string sku) => _products.GetValueOrDefault(sku);

/// <summary>Products in stock, ordered by name.</summary>
public IReadOnlyList<Product> InStock() =>
_products.Values.Where(p => p.Stock > 0).OrderBy(p => p.Name).ToList();

public IReadOnlyCollection<Product> All => _products.Values;
}

Values, Booleans and Nulls

The first test raises a price by a percentage. The method rounds to two decimal places, so the result is predictable:

M02.XUnitBasics/Product.cs

/// <summary>Applies a percentage-based price increase.</summary>
public void IncreasePriceByPercent(decimal percent)
{
Price = decimal.Round(Price * (1 + percent / 100m), 2, MidpointRounding.AwayFromZero);
}

Keep in mind that every xUnit assertion throws an exception when it fails. The test stops at the first failed assertion, and later assertions in the same test do not run. That is one more reason to order assertions from the most basic fact to the most detailed one.

M02.XUnitBasics.Tests/CoreAssertionTests.cs

[Fact]
public void Equal_ComparesValues()
{
var product = new Product("MOUSE-01", "Kablosuz Mouse", 250m, 5);
product.IncreasePriceByPercent(20m);

Assert.Equal(300m, product.Price);
Assert.NotEqual(250m, product.Price);

// For decimal/double comparisons you can specify precision:
Assert.Equal(300.001m, product.Price, precision: 2);
}

[Fact]
public void TrueFalse_ForBooleanContracts()
{
var product = new Product("MOUSE-01", "Kablosuz Mouse", 250m, 5);

Assert.True(product.Stock > 0, "Ürün stokta olmalıydı.");
Assert.False(product.Stock == 0);
}

[Fact]
public void NullNotNull_ForOptionalResults()
{
var catalog = new Catalog();
catalog.Add(new Product("MOUSE-01", "Kablosuz Mouse", 250m, 5));

Assert.NotNull(catalog.Find("MOUSE-01"));
Assert.Null(catalog.Find("YOK-01"));
}

Assert.Equal is the workhorse. It uses the type's equality, so for numbers and strings it compares values. The precision overload rounds both values to the given number of decimal places before comparing, which is how you compare computed decimal or double results without failing on tiny rounding differences.

Assert.True and Assert.False are for real boolean contracts. When you do use them on an expression, pass a message as the second argument (here "the product should have been in stock"). It is the only context the failure will have. If you find yourself writing Assert.True(x == y), use Assert.Equal(y, x) instead.

Find returns Product?, so a missing SKU is a normal result, not an error. Assert.Null and Assert.NotNull state that contract directly. Assert.NotNull also helps the compiler: after it, nullable analysis treats the value as not null.

Same vs. Equal: References and Values

M02.XUnitBasics.Tests/CoreAssertionTests.cs

[Fact]
public void SameNotSame_CompareReferences()
{
var catalog = new Catalog();
var product = new Product("MOUSE-01", "Kablosuz Mouse", 250m, 5);
catalog.Add(product);

// Same: is it the SAME object? (reference equality)
Assert.Same(product, catalog.Find("MOUSE-01"));

// NotSame: objects with equal values but different instances.
Assert.NotSame(product, new Product("MOUSE-01", "Kablosuz Mouse", 250m, 5));
}

Assert.Same checks reference identity: both variables point to the same object in memory. Assert.Equal checks equality as the type defines it. Use Same when identity is part of the contract, as it is here: the catalog must hand back the instance you stored, not a copy. Use Equal when only the value matters. Because Product is a class without custom equality, two products with identical data are not equal, and they are certainly not the same.

Collections

M02.XUnitBasics.Tests/CoreAssertionTests.cs

[Fact]
public void ContainsDoesNotContain_ForCollections()
{
var catalog = new Catalog();
var mouse = new Product("MOUSE-01", "Kablosuz Mouse", 250m, 5);
catalog.Add(mouse);

Assert.Contains(mouse, catalog.All);
Assert.DoesNotContain(catalog.All, p => p.Sku == "YOK-01");
}

[Fact]
public void EmptyNotEmptySingle_DescribeCollectionSize()
{
var catalog = new Catalog();
Assert.Empty(catalog.InStock());

catalog.Add(new Product("MOUSE-01", "Kablosuz Mouse", 250m, stock: 5));
Assert.NotEmpty(catalog.InStock());

// Single both says "there is exactly one element" and returns that element.
var only = Assert.Single(catalog.InStock());
Assert.Equal("MOUSE-01", only.Sku);
}

[Fact]
public void AllAndCollection_WhenEveryElementMatters()
{
var catalog = new Catalog();
catalog.Add(new Product("A-1", "Ampul", 30m, 4));
catalog.Add(new Product("B-1", "Bant", 15m, 9));
catalog.Add(new Product("C-1", "Cetvel", 8m, 0)); // out of stock

// All: check the same rule for every element.
Assert.All(catalog.InStock(), p => Assert.True(p.Stock > 0));

// Collection: use it when the element COUNT and ORDER are part of the contract.
// InStock() returns items ordered by name, so the order is meaningful.
Assert.Collection(
catalog.InStock(),
first => Assert.Equal("Ampul", first.Name),
second => Assert.Equal("Bant", second.Name));
}

Contains has two forms: one takes an item, the other a predicate. Empty, NotEmpty and Single describe the size of a collection. Single is especially handy because it returns the element, so the next assertion can inspect it.

Assert.All and Assert.Collection look similar but answer different questions. All applies one rule to every element and reports every element that fails. It does not care about count or order. Collection takes one inspector per element, in order, and fails if the count differs. Choose Collection when order is part of the contract, as it is for InStock(), which promises results sorted by name. Choose All when every element must satisfy the same rule regardless of position.

Structural Comparison with Equivalent

M02.XUnitBasics.Tests/CoreAssertionTests.cs

[Fact]
public void Equivalent_ComparesObjectGraphsStructurally()
{
var actual = new { Sku = "A-1", Tags = new[] { "yeni", "indirimli" } };

// Equivalent: do they have the same structure? (content comparison, not references)
Assert.Equivalent(new { Sku = "A-1", Tags = new[] { "yeni", "indirimli" } }, actual);
}

Assert.Equivalent compares object graphs member by member, including nested arrays. Assert.Equal on the two anonymous objects would fail: the compiler-generated Equals of an anonymous type compares each property with default equality, and two different arrays are only equal by reference. Equivalent walks into the arrays and compares their content. It is useful for DTOs and results without custom equality. Use it with care: a broad structural comparison checks many members at once and can hide which one the test is really about.

Summary

  1. Pick the narrowest assertion that explains the failure. Assert.Single(list) beats Assert.True(list.Count == 1).
  2. Assert.Equal compares values. The precision overload handles computed decimals and doubles.
  3. Assert.Same checks reference identity, Assert.Equal checks equality. Use Same only when identity is part of the contract.
  4. Use Assert.Collection when count and order matter, and Assert.All when one rule applies to every element.
  5. Assert.Equivalent compares object graphs structurally, without needing custom equality.