.NET, C#, CSharp, Library, Programming, Tests, Unit tests

Fluent Assertions in unit tests

As a continouation of the article about unit test frameworks I would like to introduce Fluent Assertions. This framework simplifies testing by BDD style syntax. Let’s start from basic assertion.

var result = 1+1;
result.Should().Be(2);

As you noticed, first is going the result, then the keyword (or rather extension method) Should() and at the end the condition (so in case of equal it is Be(expectedValue)).

You can chain assertions using And property (AndConstraint) instead of using multiple assertions in one test method.

var value = "sample string";
value.Should().Contain("sample").And.NotContain("int");

So it is simple as that 🙂 Now you are just limited by your imagination.

Special cases

There is few special cases which are often problematic like assert if exception was thrown or validate the collection.

Exceptions

Sometimes we would like to test a method which throws exceptions. It is usually a bit tricky. That what we need is a reference to an action. Below sample is just a basic way.

Action mathOperation = () => Math.Round(1d, -1);
mathOperation.Should().Throw<ArgumentOutOfRangeException>();

It is just a basic way to check if particular type of exception was thrown. It is possible to check also the message using WithMessage(expectedMessage).

Collections

I will not analyze simple cases like Equal() or Contain(), just to focus on interesting and usefull cases.

  • ContainInOrder(expectedCollection) – compares the collections in the given order
  • OnlyHaveUniqueItems() – checks if collection has only unique items
  • NotBeNullOrEmpty() – checks if collection is null or empty
  • BeInAscendingOrder(), BeInDescendingOrder(), NotBeAscendingInOrder(), NotBeDescendingInOrder() – checks if items are (not) in the particular order

Summary

I think that FluentAssertion is cool library. I never measured its performance however it never caused a problem to any of my teams which were using it. Also important benefit is easier change of unit test framework (yes, I know – that happens rarely but sometimes it is done).

Links

FluentAssertions web site.

Leave a Reply

Your email address will not be published. Required fields are marked *