Skip to content

Assertions

Aligned verification in all our tests will improve its readability. That's why everyone should use FluentAssertion in all cases. The only exception are special methods for Mock like Verify(). Other methods like xUnit Assert.Equal(0, 1) is not allowed.

Basic assertionsπŸ”—

All assertions starts with Should().

var firstValue = 1;
var secondValue = 2;

var result = firstValue + secondValue;

result.Should().Be(3);

Info

Most usable assertions are - Be, BeNull, BeTrue, BeFalse, BeOfType. Read Basic Assertions article for more info.

Error messageπŸ”—

If you have a complicated assertion describe it with an error message

IEnumerable<int> numbers = new[] { 1, 2, 3 };
numbers.Should().HaveCount(4, "because we thought we put four items in the collection"); // fail
This rise an error: β€œExpected numbers to contain 4 item(s) because we thought we put four items in the collection, but found 3.”

Assertion chainπŸ”—

You could add And to chain assertions for the same object.

string actual = "ABCDEFGHI";
actual.Should().StartWith("AB").And.EndWith("HI").And.Contain("EF").And.HaveLength(9);
Or Which to check child members of the object
dictionary.Should().ContainValue(myClass).Which.SomeProperty.Should().BeGreaterThan(0);
someObject.Should().BeOfType<Exception>().Which.Message.Should().Be("Other Message");
xDocument.Should().HaveElement("child").Which.Should().BeOfType<XElement>().And.HaveAttribute("attr", "1");

Assertion scopeπŸ”—

You can batch multiple assertions into an AssertionScope so that FluentAssertions throws one exception at the end of the scope with all failures.

using (new AssertionScope())
{
    5.Should().Be(10);
    "Actual".Should().Be("Expected");
}

Info

Read Assertion Scopes article for more info.

Assert mock method callsπŸ”—

Use Verify for the assertion of mock methods calls.

var loggerMock = new Mock<ILogger>();

loggerMock.Object.Debug("123");

loggerMock.Verify(l => l.Debug("123"), Times.Once);

Info

Read Verification article for more info.