Skip to content
Cyrille DUPUYDAUBY edited this page Nov 22, 2020 · 4 revisions

Your first checks

NFluent offers dozens of specialised checks to help you have clear and explicit unit tests. Newcomers may find this overwhelming and be left wondering how to navigate in this jungle. This page is here to guide them and help them focus on the most important things first

Expected results

Proper unit tests use explicit and constant values to describe the expected results. It typically means providing constant input (as parameters for example) and expecting a constant output.

Let's assume you are working on desktop calculator that is expressed as a single method:

class DeskCalculator
{
    public double ComputeOperation(char operator, double firstOperand, double otherOperant);
}

So you may need to check all the basic operations, using 4 and 2:

public void TestCalculator()
{
  var deskCalc = new DeskCalculator();
...
  // 4.0 + 2.0 == 6.0
  Check.That(deskCalc.ComputeOperation("+", 4.0, 2.0)).IsEqualTo(6.0);
  // 4.0 * 2.0 == 8.0
  Check.That(deskCalc.ComputeOperation("*", 4.0, 2.0)).IsEqualTo(8.0);
}

So the check you are going to use 80% of the time is IsEqualTo. But...

For some types of object, equality may be a bit too strict. For example:

  • double (float) computation introduce various rounding errors along the calculation or give results that cannot be exactly represented in binary (see Wikipedia)
  • result may be provided as an enumeration, but the order is not important *...

Here are the other checks you will find useful:

  • IsCloseTo: checks if the provided number is close to the expected value, where close is defined by a tolerance that you provide. Example:
Check.That(sut).IsCloseTo(.1, .02);
// sut can be between .08 and 0.12
  • IsEquivalentTo: checks if an enumeration (including arrays and dictionary) have the expected contents, disregarding the insertion order.
Check.That(sut).IsEquivalentTo(new [] {1,2,3})
// sut can be: 1,2,3 - 1,3,2 - 2,1,3 - 2,3,1 - 3,1,2 - 3,2,1 
  • IsTrue, IsFalse: more explicit that IsEqualTo(true/false). Note that you should not use these for arbitrary conditions, i.e.
// stop doing that
Check.That(sut>10).IsTrue(); // hard to read, plus error messages won't be useful
// start doing that
Chek.That(sut).IsStrictlyGreaterThan(10); // explicit and the error message will reflect the rule