简体   繁体   中英

NUnit: Should I check that objects are not null before using them in asserts?

I'm writing a test that calls a method that may potentially return null. In this specific test, the returned object must not be null and some property on it must match a specific value. Example:

var obj = thing.GetObject();
Assert.That(obj, Is.Not.Null);
Assert.That(obj.Name, Is.EqualTo("Name"));

This is a habit of mine from C++, where you'd normally have an assertion prior to using a pointer since accessing null can crash the unit test (and you'd want to avoid doing that). In C#, however, accessing null objects is a normal exception. Is it a good practice to do what I've done above, or just go ahead and access the object and rely on the exception to fail the test case if the object is null? As in:

var obj = thing.GetObject();
Assert.That(obj.Name, Is.EqualTo("Name")); // Throws if `obj` is null

I'm no authority on the matter but I think you'll get more meaningful and consistent test result messages if you assert that it's not null instead of letting it throw an exception. I do it in my own unit tests, for what it's worth.

A NullReferenceException is a sign that you missed something. Asserting that the result is not null before testing the property is not missing that something.

It depends, I'm afraid.

In the example you give, there is no initial setup, yet you state that the method called may sometimes return null. Without that setup, you can't test for null or non-null, because (as stated) either is possible. Such a test is not useful.

OTOH in the real test, you will have done setup and should actually know what result you expect. In that case, test for it, just as you have done.

You should also have a test where the object is set up to return null and test for that situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM