Jan 15 2018

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".

Permanent link to this article: https://www.productivecsharp.com/2018/01/careful-using-c-null-conditional-operators-tests/

  • Meir Blachman says:

    I’ve built something similar in the library https://github.com/fluentassertions/fluentassertions.analyzers

  • >