Skip to content

Collections ​

EnumerableAssertions<TEnumerable, T> is available for any IEnumerable<T> via .Should().

Sequence Equality ​

By default, ordering is strict — elements must appear in the same order.

csharp
var numbers = new[] { 1, 2, 3 };

numbers.Should().SequenceEqual(1, 2, 3);   // passes
numbers.Should().SequenceEqual(3, 2, 1);   // fails — wrong order
numbers.Should().NotSequenceEqual(4, 5, 6);

Pass a collection as the expected value, or use a custom IEqualityComparer<T> or predicate:

csharp
IEnumerable<string> actual = new[] { "a", "b", "c" };
IEnumerable<string> expected = new[] { "A", "B", "C" };

actual.Should().SequenceEqual(expected, StringComparer.OrdinalIgnoreCase);

actual.Should().SequenceEqual(expected,
    (a, b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase));

See SequenceEqual and NotSequenceEqual.

Contains ​

csharp
var numbers = new[] { 1, 2, 3 };

numbers.Should().Contain(2);
numbers.Should().NotContain(5);

With a custom comparer or predicate:

csharp
IEnumerable<string> items = new[] { "Hello", "World" };

items.Should().Contain("hello", StringComparer.OrdinalIgnoreCase);
items.Should().Contain("hello", (a, b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase));

See Contain and NotContain.

Single Item ​

Assert that the collection contains exactly one element using ContainSingle:

csharp
var single = new[] { 42 };
single.Should().ContainSingle().And.Equal(42);

Or exactly one element matching a predicate:

csharp
var numbers = new[] { 1, 2, 3 };
numbers.Should().ContainSingle(x => x > 2).And.Equal(3);

All Items Satisfy a Predicate ​

csharp
var numbers = new[] { 2, 4, 6 };
numbers.Should().OnlyContain(x => x % 2 == 0);

The error message includes the predicate expression text and the first failing item's index. See OnlyContain.

Count ​

These methods from CountExtensions work on any IEnumerable (not just generic), and use ICollection.Count when available for efficiency:

csharp
IEnumerable<int> items = new[] { 1, 2, 3 };

items.Should().HaveCount(3);
items.Should().NotHaveCount(5);
csharp
items.Should().BeEmpty();         // fails — has 3 elements
new int[0].Should().BeEmpty();    // passes
items.Should().NotBeEmpty();      // passes

Non-Generic Enumerables ​

For legacy non-generic IEnumerable types, use the extension methods from EnumerableExtensions:

csharp
System.Collections.IEnumerable legacy = new ArrayList { 1, 2, 3 };

legacy.Should().SequenceEqual(1, 2, 3);
legacy.Should().NotSequenceEqual(4, 5, 6);

Chaining ​

Chainable methods return an AssertionsChain<TAssertions, T>:

csharp
new[] { 1, 2, 3 }
    .Should()
    .NotBeNull()
    .And.HaveCount(3)
    .And.Contain(2);