Skip to content

NFluent's assertions structure

Bartosz Jarmuż edited this page Apr 17, 2020 · 7 revisions

Generalities

  • NFluent assertions are referred to as checks.
  • An assertion can combine one or more checks using And or Which keywords.
  • Writing an assertion: To write an assertion you need to capture what needs to be evaluated (referred to as system under test or sut for short).

Check the sut

A few capturing methods are provided.

Check.That

This is the most used one. You shoud use it by default and use a specialized one when needed. Example

var myItem = new Myclass();
...
Check.That(myItem).IsInstanceOf<MyClass>();

If you want to perform checks on a Type, you can use the parameterless overload, such as:

Check.That<MyClass>().IsInstanceOf<Type>();

Check.ThatCode

This one must be used to test portion of code or a delegate. Example:

Check.ThatCode ( () =>
    {
      ...
      throw new ApplicationException();
    }
   ).Throws<ApplicationException>();

Check.ThatAsyncCode

This one must be used to test asynchronous code/delegate lambda. Since V2.3, you can also use Check.ThatCode() for asynchronous code.

Check.ThatDynamic

This one must be used to capture dynamics type, otherwise you will have compilation errors due to how dynamic types are implemented in .Net.

Check.ThatEnum

This one can be used on value types, such as structs or enums. While those types can be checked with Check.That, Check.ThatEnum offers some enum/struct specific checks.

Assumptions (V2.6)

NFluent supports assumptions like check. Assumptions are used to verify that some preconditions are met. If they are not met, the test is marked as inconclusive. An example of usage is to verify that some API is available/up. Note that this features works only with unit testing framework that offers assumption (NUnit and MsTest). When using xUnit or an unknown testing framework, the test will appear as failed.

Writing an assumption is no more difficult that writing a check. You need to start the assumption with Assuming instead of Check.

// always triggers an inconclusive test
Assuming.That(true).IsEqualTo(false);
Clone this wiki locally