February 2

The Future of Engineering at Redgate — A futurespective empathy map approach

0  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

Agile, Redgate, Software Engineering


You may also like

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

>