The constraint-based assert model

In NUnit 3.0 and higher assertions are primely written using the constraint-based assert model. People using NUnit before this version where used to the classic model which used constructions like this:

const int expectedValue = 2;
Assert.IsEqual(expectedValue, myObject.MyMethodReturningInt());

Can be constructed the following way using the constraint-based assert model (CBAM):

const int expectedValue = 2;
Assert.That(myObject.MyMethodReturningInt(), Is.EqualTo(expectedValue);

Readability

One of the things that is most notable is the readability of the CBAM. If you read the 2nd syntax, you can read in a more natural way that some value is expected and it is (should be) equal to the expected value.

Cleaner interface

Using the classic assertions, you have to look into the documentation of the assert method which parameter should contain the expected value and which one the actual value. In this way the interface of the method is much cleaner compared to the classic one.

Also there are less different methods within the Assert class that can be used. A single That method can be used to cover all cases.

Converting from classic to constraint-based assert model

NUnit provides a tool to convert the classic assert to CBAM. It is an analyzer which has rules and associated code fixes to detect the classic assertions.

Which model should you learn?

To the question which model you should learn and/or use, I would say the CBAM. Within NUnit it has replaced the classic model, so support will be available much longer for CBAM. Also in the end you will find more people answering questions on the internet using snippets containing CBAM instead of the classic model.

Posted in NUnit by Bruno at March 29th, 2024.

Leave a Reply