January 15

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

2  comments

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. 

So...

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




Tags

.NET, C#, C# 7, Testing


You may also like

The best way to stay up to date with C# 10 features

My Technical Journey from my first program to Lead Software Engineer

Top 10 C# Developer News from Microsoft Build 2020

Agile Estimation

  • 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”

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

    Subscribe to our newsletter now!

    Get instant access to the Master C# 9 webinar to learn all the new exciting C# 9 features quickly.
    Get regular videos and news on C# and .NET and offers on products and services to master C#.

    We will collect, use and protect your data in accordance with our Privacy Policy.

    >