Be careful in using the C# null conditional operators in tests

Few days ago, I come across to a bunch of tests that were using the null conditional operator in the wrong way and I think it is worth sharing it.

Have a look at this code and how I fixed it.

Dangerous use of null C# conditional operator in test

What's the problem with the original code?

When result is null, the test pass even if clearly shouldn't!

The reason is because of the "short-circuiting" behaviour.

When result is null, then the rest of the chain’s execution stops! The test then pass because the method ends and by default a test without assertions is a pass.

You can learn more about "short-circuiting"  with null conditional operators here

How did I fix it?

In this particular case I have just removed the null conditional operator and performed a simple comparison using equality instead of relying on calling ToString. 


Be careful when using null conditional operators in assertions and remember about "short-circuiting".

Sharing is Caring
  • Meir Blachman says:

    I’ve built something similar in the library

  • I think this is more a problem of design … the test “ShouldBe” is written as an extension method and this is the man trap.

    Your blog article would arguably be better named “Be careful using extension methods for unit testing”

  • >