Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Upgrade 4 to 5

This is a work in progress. Please send a PR with any amendments.

Changes that don't announce themselves

Most of what follows shows up as a compile error or a failing test, which tells you where to look. A few changes don't: a test that passed in v4 still passes in v5, and checks less than it did. These are the ones to look for by hand:

Using Newtonsoft.Json? Add one line

v4 compared JToken values (including JObject, JArray and JValue) with their own Equals, through the ShouldlyConfiguration.CompareAsObjectTypes list, which held Newtonsoft.Json.Linq.JToken by default. v5 removes that list and knows nothing about Newtonsoft.Json. Without the line below, Shouldly compares tokens element by element, which only compares their shape: JToken.Parse("{\"a\":1}").ShouldBe(JToken.Parse("{\"b\":2}")) passes. Register JToken.DeepEquals once in your test project:

[ModuleInitializer]
internal static void Initialize() =>
    ShouldlyConfiguration.UseEquality<JToken>(JToken.DeepEquals);

This is also better than v4. JToken.Equals only compares JValues by value; for JObject and JArray it is reference equality, so in v4 two equal JSON objects failed ShouldBe, and the registration only applied when the static type was exactly JToken. With the rule, tokens compare as JSON wherever ShouldBe and its relatives meet them: as values, collection elements, dictionary values, and in ShouldContain and the other membership assertions. ShouldBeEquivalentTo uses the rule too, so a token inside an object graph is compared as JSON; without the rule it can't compare a JToken at all.

Using System.Text.Json? Nothing to add

Neither JsonNode nor JsonElement defines equality, so in v4 two values holding the same JSON were never equal, to ShouldBe or to ShouldBeEquivalentTo. On .NET 8 and later, v5 compares two of them as JSON in every assertion, with nothing to register:

A test that newly fails is a ShouldNotBe between two values that hold the same JSON. See System.Text.Json, including what to register on .NET Framework.

CompareAsObjectTypes is replaced by UseEquality

ShouldlyConfiguration.CompareAsObjectTypes is removed. Register an equality rule instead, which says what equality means rather than naming a type:

A rule covers the type and its subtypes, and applies everywhere Shouldly compares values: v4's list was matched by exact name against the static type, and only by ShouldBe. So ShouldNotBe, collection elements, dictionary values and the membership assertions now agree with ShouldBe, and a type argument such as bag.ShouldBe<IdBag>(other) is no longer needed to stop an enumerable type being compared by its items.

Libraries built against v4 must be recompiled

Most assertion signatures changed in v5: they gained [CallerArgumentExpression] parameters, params arrays became collections, and the dictionary assertions also take any IEnumerable<KeyValuePair<TKey, TValue>>. Once the changes in this guide are applied, most code compiles against v5, but assemblies compiled against v4 are not binary compatible. A shared library of custom assertions or test helpers built against Shouldly 4 fails at runtime with MissingMethodException when loaded alongside Shouldly 5. Rebuild such libraries against v5.

ShouldBeOneOf and friends take a collection, not params

ShouldBeOneOf, ShouldNotBeOneOf, and ShouldBeOfTypes were variadic in v4. In v5 they take their candidates as a single collection, so call sites passing individual values fail with CS1503:

Wrap the values in a collection expression, or in new[] { … } below C# 12. Call sites that already pass an array or a collection expression are unaffected.

This is the most widely hit compile break in the upgrade — ShouldBeOneOf(a, b, c) was the canonical v4 spelling — but it is a purely mechanical fix and the compiler points at every occurrence.

The params array was dropped because a params parameter must come last, which leaves no room for the [CallerArgumentExpression] parameter these assertions now carry. That parameter is why the failure message reports your source text:

ShouldSatisfyAllConditions is obsolete

ShouldSatisfyAllConditions still works, but it is marked [Obsolete], so builds that treat warnings as errors fail with CS0618. It cannot capture the asserted expression via [CallerArgumentExpression] and falls back to stack-trace parsing, which is not trim- or AOT-safe. Use ShouldSatisfy when the conditions share a subject, and Should.Satisfy for a group of unrelated assertions:

Exception assertions no longer accept a Task instance

Should.Throw, Should.ThrowAsync, Should.NotThrow, and Should.NotThrowAsync — and the ShouldThrow, ShouldThrowAsync, ShouldNotThrow, and ShouldNotThrowAsync extension methods — had overloads that accepted a Task (or Task<T>) instance alongside the ones that accept a Func<Task>. In v5 the Task-instance overloads are obsolete at error level, so call sites fail with CS0619:

The Task overloads were a pit of failure. Their argument is evaluated before Shouldly is called, so anything thrown while producing the task escapes the assertion. That is the normal shape for eager argument validation on a Task-returning method:

There is no state machine to catch that throw, so Should.Throw<ArgumentNullException>(service.SaveAsync(null)) fails with an unhandled ArgumentNullException instead of passing, and Should.NotThrow(service.SaveAsync(item)) reports a bare exception rather than a Shouldly failure message.

Mark the same method async and it behaves: the compiler-generated state machine captures the exception into a faulted task, which the Task overload awaits and reports correctly. Whether the overload works at all therefore hinged on an implementation detail of the method under test — one the test cannot see. The Func<Task> overloads invoke the delegate inside the assertion, so the synchronous throw and the faulted task are both caught either way. The two spellings differ only by a pair of parentheses, which is why the wrong one was so easy to reach for.

Pass a method group or a lambda. If you already hold a Task, wrap it: Should.Throw<ArgumentNullException>(() => task). The compiler error message carries the same instruction.

Exception assertions passed a Type now match derived exceptions

In v4 the generic and Type-taking exception assertions disagreed. Should.Throw<ArgumentException>(...) passed when an ArgumentNullException was thrown, because it matched like a catch clause, but Should.Throw(..., typeof(ArgumentException)) failed, because it required the exact type. In v5 both forms match any exception assignable to the expected type:

This covers Should.Throw, Should.ThrowAsync, ShouldThrow, and ShouldThrowAsync, with and without a timeout. Assertions that failed only because the thrown type was a subclass now pass.

If you relied on the exact match, use ThrowExactly, which is new in v5. It has the same overloads as the generic Throw, plus ThrowExactlyAsync and the ShouldThrowExactly and ShouldThrowExactlyAsync extension methods:

If the type is only known at run time, assert on the type of the returned exception:

Relatedly, a task that is cancelled by throwing an OperationCanceledException subclass is now reported with that original exception by the synchronous Should.Throw(Func<Task>) overloads. In v4 it was replaced with a new TaskCanceledException.

Exception assertions on a Func<Task> no longer unwrap an AggregateException

In v4 the synchronous Should.Throw and ShouldThrow overloads that take a Func<Task> unwrapped an AggregateException to its first inner exception, even when the code under test threw the AggregateException itself. In v5 they report the exception the way await and Should.ThrowAsync do, so an AggregateException the code throws is kept:

This covers the generic and Type-taking forms, with and without a timeout. If you asserted on the inner exception, assert on the AggregateException and then on its InnerException.

String assertions default to case-sensitive comparison

ShouldContain, ShouldNotContain, ShouldStartWith, ShouldEndWith, ShouldNotStartWith, and ShouldNotEndWith defaulted to Case.Insensitive in v4, while ShouldBe compared case-sensitively. In v5 all string assertions are case-sensitive by default, aligning with ShouldBe, C# string semantics, and other assertion libraries. Case.Insensitive remains available as an opt-in.

The first three fail on upgrade and point at themselves: the failure message shows where the text was found differing only in case. Fix the casing in the test, or pass Case.Insensitive if the casing isn't what the test is about.

The negated three change without a failure. A log.ShouldNotContain("error") that rejected Error and ERROR in v4 now only rejects error, and keeps passing. Search your tests for ShouldNotContain, ShouldNotStartWith and ShouldNotEndWith on strings, and where the test means any casing, say so:

Failure messages look different

If you snapshot or otherwise assert on Shouldly's failure messages, expect them to change:

  • String differences are shown with ▼/▲ markers pointing at the differing characters, replacing v4's index/character-code table. Multi-line strings get a line-based diff. Set ShouldlyConfiguration.DiffStyle to DiffStyle.Ascii if your terminal can't render the arrows, and EscapeStyle to change how control characters are shown.

  • DateTimeOffset values are rendered in the round-trip "o" format (2000-01-01T00:00:00.1230000+00:00), matching DateTime. v4 used the current culture's ToString(), which dropped sub-second precision, so two values differing by milliseconds printed identically. Update any message scrubbers that format DateTimeOffset with ToString().

  • ShouldNotBe and ShouldNotBeSameAs on collections no longer print a difference section, which had nothing to mark since the values are equal. ShouldNotBe with a comparer says but was (using a custom comparer).

  • ShouldBe says why two values that read the same are unequal, in a closing line such as but they are different types (expected System.Int32, actual System.Numerics.BigInteger) or but at Lines, they are different instances, and List<String> compares by reference; use ShouldBeEquivalentTo to compare members. v4 printed the same text on both sides and nothing else.

  • ShouldBe on collections says first difference at index 57 when the first difference is past the tenth item, and why the two items there are unequal when they read the same. A difference section in which nothing would be marked is left out, as when an equality rule judged the two collections whole, or the first difference is after the items shown.

  • ShouldBeSameAs ends with which is a different instance, adding (the two are equal by value) when they are, instead of a difference section on collections.

  • ShouldNotBeOfType and ShouldNotBeAssignableTo show the actual value's type, as ShouldBeOfType and ShouldBeAssignableTo do. v4 showed the value.

  • ShouldStartWith and ShouldNotStartWith end but did not and but did when the subject already shows the value, as ShouldEndWith does. v4 ended but was not and but was.

  • Case-sensitive ShouldContain, ShouldStartWith and ShouldEndWith on strings end with found differing only in case at index 12 and the text found there, when ignoring case would have passed. ShouldContain then centres the excerpt of a long actual value on that text, rather than cutting it from the start. String ShouldBe says which differs only in case when that is all that tells the two strings apart.

  • ShouldNotBeNullOrWhiteSpace shows the failing value. v4 showed (null) whatever the value was.

  • Should.ThrowAsync(Func<Task>, Type) reports a different exception type as Task `expr` should throw … but threw …. v4 worded it throw async internal.

String failure messages echo less of the value

In v4, ShouldBe on strings echoed the actual and expected values up to a hardcoded 5000 characters, silently, and computed the difference section from those already-truncated values. Two long strings differing past character 5000 therefore produced a 10 KB message showing two identical-looking values and no difference at all.

In v5 the difference is always computed from the full values, and only the echo is clipped — to ShouldlyConfiguration.MaxStringLengthInMessages, which now defaults to 1000. Truncation is announced rather than silent:

Messages for long strings get substantially shorter, and the difference section carries the information the raw echo used to bury. If you were relying on the old volume of output, set ShouldlyConfiguration.MaxStringLengthInMessages = 5000;.

Line-mode diffs also now cap at 20 changed lines per side, with an ... and N more line(s) marker.

Collection failure messages are capped

v4 echoed every item of a collection in a failure message, and buffered or counted a lazy sequence in full to describe it, so ShouldBe on an infinite sequence never returned. In v5 messages show at most ShouldlyConfiguration.MaxEnumerableItemsInMessages items (default 1000, which the difference section was already limited to) followed by ..., and read a sequence no further than that. Collections within the limit are reported exactly as before.

Dictionary value assertions compare values structurally

ShouldContainKeyAndValue and ShouldNotContainValueForKey compared the value with object.Equals in v4, while the rest of the library — including ShouldBe on the very same value — goes through Shouldly's structural comparer. A collection-valued dictionary therefore behaved differently depending on which assertion you reached for:

In v5 both assertions compare the value the way ShouldBe does: collections element-wise, numerics across types and honouring ShouldlyConfiguration.DefaultFloatingPointTolerance, then the type's own equality ahead of CompareTo. string keeps comparing with its own Equals, and a type with an equality rule with its rule, as under ShouldBe.

This is not member-wise comparison. A value that isn't a collection is compared with its type's IEquatable<T> or overridden Equals, or with CompareTo when it defines neither, and otherwise with object.Equals, so a reference type that defines none of them compares by reference. (Member-wise remains ShouldBeEquivalentTo.)

The break runs in both directions, wherever Equals and structural equality disagree. The common direction is the one above — two structurally-equal but distinct instances, which makes ShouldContainKeyAndValue start passing and ShouldNotContainValueForKey start failing. The reverse happens when a value's Equals reports equality the structural walk doesn't: a collection type that overrides Equals to compare only an id, say, is now walked element-wise, so ShouldContainKeyAndValue can go from passing to failing. If a dictionary value assertion changes result on upgrade, check it against dictionary[key].ShouldBe(value) — that is now the definition.

Key lookup is unchanged — ShouldContainKey and friends still defer to the dictionary's own key comparer.

ShouldBe compares dictionary entries by key and value

ShouldBe walks a dictionary entry by entry, and each entry is a KeyValuePair<TKey, TValue>. v4 compared those with the struct's own Equals, which compares a collection-typed value by reference, so two dictionaries with equal contents failed. The failure message printed both sides identically:

In v5 a KeyValuePair is compared as its key and its value, each the way ShouldBe compares a single value: collections element-wise, numerics across types (a Dictionary<string, object> holding 1 equals one holding 1L), then the type's own equality ahead of CompareTo. A string key or value keeps comparing with its own Equals, and one with an equality rule with its rule. dictionary.ShouldBe(other) now agrees with dictionary[key].ShouldBe(value) and with ShouldContainKeyAndValue. This applies anywhere pairs are compared: dictionaries, other IEnumerable<KeyValuePair<TKey, TValue>> sequences, ignoreOrder: true, and a single KeyValuePair passed to ShouldBe. The difference line and the is missing lists mark only the entries that really differ.

A comparer you pass to ShouldBe still decides on its own.

A test that newly fails is usually a ShouldNotBe on dictionaries whose values are collections, which was passing only because v4 compared those values by reference.

ShouldBe compares dictionaries and sets in any order

v4 compared dictionaries and sets in the order they enumerate in, which is an implementation detail of the collection, so equal contents could fail:

In v5, ShouldBe and ShouldNotBe match the entries of dictionaries (IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> or IDictionary) by key and compare the values, and match the elements of sets (ISet<T> or IReadOnlySet<T>) in any order. This applies at any depth, such as a dictionary in a list. Keys are compared the way ShouldBe compares any value, not with either dictionary's own key comparer. The failure message lists each key that is missing, isn't expected or has a different value, instead of marking positions:

Order is also ignored when only one side is a dictionary or a set and the other a list, an array or a LINQ query, as a HashSet or a Dictionary has no order to compare with a list's. A sorted or ordered collection does (SortedSet, SortedDictionary, SortedList, the immutable sorted collections, OrderedDictionary, or any dictionary or set that can be indexed by position), so against a list it is still compared in order, as in v4. See Dictionaries and sets.

A test that newly fails is a ShouldNotBe between a dictionary or set and a collection that holds the same items in a different order.

ShouldBe compares tuples item by item

A ValueTuple or Tuple was compared with its own Equals, which compares each item with that item's Equals, so a tuple holding a collection compared it by reference, and numbers didn't compare across types. Both sides printed identically:

In v5 a tuple is compared item by item, as a KeyValuePair is: each item the way ShouldBe compares a single value, an equality rule for an item's type included. This applies to tuples of any arity, named tuples, tuples nested in tuples, and tuples in sequences, dictionaries and membership assertions. A ValueTuple is never equal to a Tuple, nor a tuple to one of a different arity, and a comparer you pass to ShouldBe still decides on its own.

Comparing each item as a single value also means that a float or double item is now compared within DefaultFloatingPointTolerance, where the tuple's own Equals compared it exactly. That only matters if you have set a tolerance.

Records, anonymous types and structs keep their own Equals, which is their author's to define, so a record holding a List<T> still compares that list by reference. The failure message says so and points at ShouldBeEquivalentTo, which compares member by member (see when both values read the same).

A test that newly fails is usually a ShouldNotBe on tuples holding collections, which was passing only because v4 compared those items by reference.

Equals is always called on the expected value

ShouldBe calls Equals on the expected value (expected.Equals(actual)) and calls a custom comparer as comparer.Equals(expected, actual). v4's ShouldBe(..., ignoreOrder: true) and ShouldBeEquivalentTo's leaf comparison called it on the actual value. v5 uses the expected value everywhere.

This only changes a result when equality isn't symmetric, so that a.Equals(b) and b.Equals(a) disagree. If an assertion changes result on upgrade, the actual value's Equals accepts something the expected value's doesn't. That is usually a bug in the type under test that v4 was hiding.

ShouldBeEquivalentTo honours DefaultFloatingPointTolerance

v4's ShouldBeEquivalentTo compared float and double values exactly, ignoring ShouldlyConfiguration.DefaultFloatingPointTolerance even though ShouldBe honoured it. v5 compares them the way ShouldBe does:

This only matters if you set a non-zero default tolerance. Equivalency assertions on values that differ by no more than the tolerance now pass, wherever the value sits in the graph. With the default of 0.0 nothing changes.

Numbers of different types are compared exactly

When ShouldBe compared a float or double with a number of another type (for example, both held as object), v4 converted both sides to the floating-point type first. That conversion rounds the other side, so different numbers compared equal. A float widens to a double exactly, though, so the result depended on which types were involved:

In v5, numbers of different types are equal only when they hold the same value. This includes decimal against double: the double written 0.1 is really 0.1000000000000000055511151231257827…, so it isn't the decimal 0.1m. Compare against a value of the same type, or set ShouldlyConfiguration.DefaultFloatingPointTolerance. Under a non-zero default tolerance, mixed types are converted and compared within the tolerance, as in v4. Comparisons between values of the same type are unchanged. ShouldBeEquivalentTo and the membership assertions, which compare numbers across types for the first time in v5, follow the same rule.

ShouldBe(ignoreOrder: true) no longer passes some unequal collections

In v4, the order-insensitive comparison could treat an unmatched element as matched when the expected collection contained default(T) (0, null, and so on), so some unequal collections passed:

Tests that were passing because of this now fail, correctly.

Elements are compared with their IEquatable<T> everywhere

This only affects types whose IEquatable<T>.Equals and Equals(object) give different answers. The common case is a type that implements IEquatable<T> without overriding Equals(object), which analyzer rule CA1067 flags, so Equals(object) is still reference equality:

In v4, Shouldly honoured that Equals only where it knew the element type at compile time. Everywhere else it fell back to object.Equals, which for a class without the override means reference equality. A List<Foo> or Foo[] binds to the single-value ShouldBe<T> overload, so the comparison of two equal lists failed. (The v5 previews fixed this only on C# 13 and later, where [OverloadResolutionPriority] routes the call to the enumerable overload. On C# 12 and earlier, the default for net8.0 and .NET Framework projects, it still failed.)

In v5, when the static type doesn't say how to compare two values, Shouldly looks for an IEquatable<U> on the runtime type of the expected value, where the actual value is a U, and calls it, before Equals(object) and before CompareTo, as it would if the type were known. Types whose Equals(object) agrees with their IEquatable<T> give the same answer as before. Failure messages change in the same way: the difference line and the is missing lists of ignoreOrder: true now mark only the elements that really differ, not every element of such a type.

A test that newly fails is usually a ShouldNotBe (or ShouldNotContainValueForKey) that was passing only because the comparison fell back to reference equality. The membership assertions, ShouldContain, ShouldBeUnique and the rest, follow suit: see the next section.

A type's own Equals decides before CompareTo

This only affects types that implement IComparable<T> or IComparable and also define equality, where the two disagree. A common case sorts by one key and is equal by all its fields:

v4 asked IEquatable<T>, then IComparable<T> and IComparable, and only then Equals(object). So CompareTo decided for a type that overrides Equals, but only where the static type reached it. The same two values failed ShouldBe<object>, failed as the items of an array or a List<T>, which bind to the single-value ShouldBe<T> overload, and failed ShouldContain, which used the BCL's default equality. v5 asks the type's own equality first: IEquatable<T> (on the static type, then on the runtime type), then an overridden Equals(object). CompareTo decides only for a type that defines neither, and a struct's inherited field-by-field Equals doesn't count as defining one. Like IEquatable<T>, IComparable<T> is found on the runtime type too, so a type equal only through IComparable<T> of an interface or a base class compares the same as ShouldBe<object> or as the item of a nested collection as it does at that interface. The reverse also changes: a type whose Equals says equal while its CompareTo doesn't now passes ShouldBe.

If an assertion changes result on upgrade, check it against expected.Equals(actual) — that is now the definition. To compare with CompareTo instead, pass a comparer, or register an equality rule: ShouldlyConfiguration.UseEquality<Person>((expected, actual) => expected.CompareTo(actual) == 0).

Membership assertions compare elements the way ShouldBe does

In v4, ShouldContain, ShouldNotContain, ShouldBeOneOf, ShouldNotBeOneOf, ShouldBeSubsetOf and ShouldBeUnique compared elements with the BCL's default equality (Enumerable.Contains, Except, HashSet<T>), while ShouldBe uses Shouldly's own comparison. Two values could be equal to one assertion and unequal to the one beside it. Even the collection type mattered: ShouldContain on a List<T> honoured IEquatable<T>, while on an array it could fall back to Equals(object).

In v5, when no comparer is passed, these assertions compare elements the way ShouldBe does: collections element-wise, numerics across types and honouring ShouldlyConfiguration.DefaultFloatingPointTolerance, then the type's own equality ahead of CompareTo. Like ShouldBe, they call Equals on the expected value.

The negated forms change the other way: ShouldNotContain and ShouldNotBeOneOf can start failing, as ShouldBeUnique does above. If one of these assertions changes result on upgrade, check it against ShouldBe on the two elements — that is now the definition. To compare with the BCL's default equality instead, pass EqualityComparer<T>.Default as the comparer. The overloads that take a comparer are unchanged.

A set keeps its own membership: ShouldContain and ShouldNotContain on an ISet<T> (or IReadOnlySet<T>), or on the Keys of a Dictionary, SortedDictionary, SortedList or ReadOnlyDictionary, also count what the collection's own lookup finds, so a case-insensitive HashSet<string> still contains "A" when it holds "a". That matches ShouldContainKey deferring to a dictionary's key comparer.

Shouldly's comparison has no GetHashCode, so ShouldBeSubsetOf and ShouldBeUnique match elements pairwise: O(n·m) and O(n²). They still hash for string, enums and the built-in integral, decimal, bool, char, Guid, DateTime, DateTimeOffset and TimeSpan types (and their nullable forms), where hashing provably agrees. For a large collection of another type, pass an IEqualityComparer<T> to get hashing back.

Diff viewers need the Shouldly.DiffEngine package

In v4, a failing ShouldMatchApproved launched a diff tool through DiffEngine, which the Shouldly package depended on. In v5 the core package no longer references DiffEngine, so after upgrading no diff tool opens. Failures are still reported, and the .received file is still written. The packages DiffEngine brought in go with it, so if your tests used one without referencing it (e.g. System.CodeDom or System.Management), reference it directly.

To get the diff viewer back, install the Shouldly.DiffEngine package and turn it on once before your tests run:

The Shouldly.Configuration namespace has been removed

The approval-test configuration types — ShouldMatchConfiguration, ShouldMatchConfigurationBuilder, and friends — lived in the Shouldly.Configuration namespace in v4. In v5 they have been collapsed into the root Shouldly namespace, and Shouldly.Configuration no longer exists. (FirstNonShouldlyMethodFinder, ITestMethodFinder, and FindMethodUsingAttribute<T> are gone entirely — see ShouldMatchApproved no longer walks the stack.)

Any using Shouldly.Configuration; now fails to compile with CS0234:

Delete the using Shouldly.Configuration; line — the types resolve via using Shouldly;.

ShouldMatchApprovedDefaults has moved

The static ShouldMatchApprovedDefaults builder used to configure approval tests has moved off ShouldlyConfiguration and onto a new ShouldMatchConfiguration class. Code referencing the old accessor fails to compile with CS0117:

Change the class name only. Both types live in the root Shouldly namespace, so no using change is needed beyond using Shouldly;.

ShouldMatchApproved no longer walks the stack

In v4, ShouldMatchApproved walked the runtime stack trace to find the test method, and used its reflected declaring type, method name, and PDB source information to name and place the approval files. In v5 the test method is captured at compile time instead, via [CallerMemberName] and [CallerFilePath] parameters on ShouldMatchApproved itself. This removes the reflection dependency (ShouldMatchApproved no longer carries [RequiresUnreferencedCode], so it works under trimming and Native AOT), and no longer requires compiling with full debug information.

Two things to check when upgrading:

Approval files are now prefixed with the source file name

The default approval file name is now {SourceFileName}.{MethodName}.approved.{extension} where v4 used the declaring type's name. Under the usual one-class-per-file convention these are identical, so most suites are unaffected. If a test class lives in a file with a different name — including nested classes and multiple classes per file — the expected file name changes, and the test will fail reporting the new missing .approved file. Either rename the source file to match the class, rename the approval file to the reported name, or restore the old name with WithFilenameGenerator. Custom FilenameGenerator delegates keep compiling: TestMethodInfo.DeclaringTypeName still exists but is [Obsolete] and now returns the source file name; prefer the new TestMethodInfo.SourceFileName. TestMethodInfo's constructor is no longer public; it was only ever meant to be read from within a FilenameGenerator.

UseCallerLocation and LocateTestMethodUsingAttribute are removed

Both existed to point the stack walk at the right frame when ShouldMatchApproved was wrapped in a helper method. With compile-time capture there is no stack walk to redirect, so both now fail with CS0619. The replacement is for the helper to capture the caller info itself and pass it through:

This is the same forwarding idiom used for [CallerArgumentExpression], and unlike the v4 stack walk it is immune to inlining, async state machines, and obfuscation. Helpers nested more than one level deep forward the same two parameters at each level.

Custom assertions have a new building block and a smaller message surface

v5 adds ShouldAssertException.For, which a custom assertion throws and which lets it control the failure message: an expected value, the phrase, either value described in words, no actual line, and appended context. See Writing custom assertions.

The v4 pattern still compiles. AssertAwesomely and these message classes keep their constructors: ExpectedShouldlyMessage, ActualShouldlyMessage, ExpectedActualShouldlyMessage, ExpectedActualToleranceShouldlyMessage, ExpectedActualWithCaseSensitivityShouldlyMessage, ShouldlyThrowMessage and ExpectedEquivalenceShouldlyMessage.

The types Shouldly used internally to build its own messages are no longer public:

  • IShouldlyAssertionContext, ShouldlyAssertionContext, and the protected ShouldlyMessage.ShouldlyAssertionContext property.

  • ActualFilteredWithPredicateShouldlyMessage, AsyncShouldlyNotThrowShouldlyMessage, AsyncShouldlyThrowShouldlyMessage, CompleteInShouldlyMessage, ExpectedActualIgnoreOrderShouldlyMessage, ExpectedActualKeyShouldlyMessage, ExpectedOrderShouldlyMessage, ShouldContainWithCountShouldlyMessage and TaskShouldlyThrowMessage.

If you subclassed ShouldlyMessage and built the message from its context, move to ShouldAssertException.For. A message with its own phrase, no expected line and an appended block becomes:

The wording a message class produces depends on the name of the method that constructed it, and v5 reads that name differently:

  • Only an exact name gets a built-in assertion's wording. v4 matched names by pattern, so a custom ShouldBeNullish or ShouldContainExactly was worded like ShouldBeNull or ShouldContain. In v5 a method named exactly ShouldBeNull still is; any other name gets the plain shape of the class it constructed.

  • A name is negated when it contains the word "not". v4 looked for the letters Not anywhere, which also caught a name such as ShouldBeNoteworthy.

  • The tolerance and case-sensitivity classes always show their option. v4 dropped the tolerance or case from the message unless the method name matched a pattern. This holds for a method named like a built-in assertion too: where that assertion's wording has no place for the option, the class's own shape is used.

Custom assertion extensions no longer need [ShouldlyMethods]

In v4, custom assertion classes had to be annotated with [ShouldlyMethods] so the stack-walking machinery could tell Shouldly frames from test frames when reconstructing the asserted expression. In v5 the expression is captured at compile time with [CallerArgumentExpression], so the attribute is no longer required — a custom assertion is just an extension method. See Writing custom assertions for the v5 pattern, including how to verify your [CallerArgumentExpression] wiring with ShouldlyConfiguration.AssertCallerArgumentExpressionIsUsed().

The attribute still exists and is still honored by the legacy stack-walking fallback that only runs for netstandard2.0 consumers whose compiler does not supply caller argument expressions; keep it if your custom assertion library supports those targets.

ShouldBeEquivalentTo has been rewritten

The comparison engine behind ShouldBeEquivalentTo was rewritten for v5 (see the roadmap for the full rationale). The public API is unchanged, plus a new optional EquivalencyOptions parameter. ShouldBeEquivalentTo describes how v5 compares each kind of value. This section covers what that changes for a test written against v4.

The biggest change is which members are compared. v4 required both values to be the same runtime type. v5 takes the members from the expected value: every member on the expectation must exist and match on the actual object, extra members on the actual object are ignored, and the two needn't be the same type. This enables the most-requested scenario:

Failures now collect every difference and report them all with their paths, instead of stopping at the first. Several differences in the members of one value whose type defines its own equality, and agrees that the values differ, are reported as one difference that shows the two values and names the members (a NodaTime LocalDate differs once, not at Day, DayOfWeek and DayOfYear).

What newly passes

Most changes turn v4 failures (or crashes) into passes: cross-type and anonymous-type expectations, dictionaries compared insertion-order-insensitively with complex values compared structurally, sets compared order-insensitively, array vs List<T> with equal elements, structs and tuples holding reference-type members, types with indexers (previously NotSupportedException), Type- and Uri-valued members, and numeric members of different types holding the same value.

One of these loosens a test that already passed. In v4, actual.ShouldBeEquivalentTo(expected) also asserted that the two were the same type, and in v5 a Dog is equivalent to an expected Animal with the same name. If a test relied on that, add actual.ShouldBeOfType<Animal>().

What newly fails

  • Structs are compared by public members, not with Equals. v4 compared a class member by member and ignored its Equals, as v5 does, but compared a struct with its own Equals. So two structs that were Equals-equal while a public member differed passed in v4 and now fail, a struct whose equality depended on private state has only its public surface compared, and a struct with no public members now trips the vacuous-comparison guard below, unless it defines its own equality (IEquatable<T> or an Equals override), which is then what it is compared by. A failure where the type's own Equals calls the values equal says so: it ends by naming the type, and the rule that would compare it that way. To have a type compared by its Equals again, register an equality rule for it: ShouldlyConfiguration.UseEquality<Money>((expected, actual) => expected.Equals(actual)).

  • Multidimensional arrays check shape: a 2×3 array no longer equals a 3×2 array with the same flat content.

  • Vacuous comparisons fail. If a node selects zero comparable members (e.g. new object(), or ignoring every member via options), the assertion fails with guidance instead of silently passing. A type with no public members that defines its own equality is compared by that equality instead.

If you used a v5 preview: derived members in base-typed slots

v5 previews up to 5.0.0-preview.3 selected members from the declared type of a member or collection element, so a derived-only member of a value held as its base type or as an interface was not compared, and values held as a marker interface always failed the vacuous-comparison guard. v5 now compares them by their own type, as v4 did. An assertion that passed on a preview only because such a member was left out now fails.

Last updated