Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing checking for nulls

This is a very basic question but I still cannot find the appropriate answer. In my test there is a possibility to have null values and because of that the last stage (Act) starts looking a little bit strange (it is no longer act only). What I mean is the following:

Assert.IsNotNull(variable);

var newVariable = variable.Property;
Assert.IsNotNull(newVariable);

var finalVariable = newVariable.AnotherProperty;
Assert.AreEqual(3, finalVariable.Count);

Now they are obviously related and I have to be sure that the values are not null, but also there are three asserts in one test and the act part starts to look not right.

So what is the general solution in such cases? Is there anything smarter than 3 tests with one assert each and checks for null before the asserts of the last 2?

like image 537
Ивана Стоилова Avatar asked Nov 13 '22 22:11

Ивана Стоилова


1 Answers

Basically there are two ways of dealing with your problem:

  1. Guard assertions: extra asserts making sure data is in known state before proper test takes place (that's what you're doing now).
  2. Moving guard assertions to their own tests.

Which option to chose largely depends on code under test. If preconditions would be duplicated in other tests, it's a hint for separate test approach. If precondition has reflection in production code, it's again hint for separate test approach.

On the other hand, if it's only something you do to boost your confidence, maybe separate test is too much (yet as noted in other answers, it might be a sign that you're not in full control of your test or that you're testing too many things at once).

like image 137
k.m Avatar answered Nov 15 '22 12:11

k.m