Whether or not a value is null
could be checked implicitly like this:
assertThat(value).isEqualTo("something");
Or it could be checked explicitly:
assertThat(value).isNotNull();
assertThat(value).isEqualTo("something");
The latter makes the expectations a bit more clear, but it blows up the test code.
Is there a good reason to prefer the second approach over the first?
I suppose it ultimately comes down to preference. Technically if you’re not testing if a particular value is null, then you should test it assuming it isn’t null. The test will fail all the same, but there’s the subtle difference that you didn’t anticipate it in your test, so it is a bit like saying “There is something seriously wrong here.”
Most times, null is a possibility when things go wrong, so I check explicitly. If testing that the result is null is worth its own test, then I make an entire test testing just that. Other tests which require that it isn’t null don’t check. Ultimately it all fails, but at least in my humble opinion, it is clearer what I expect to test in this way.
If your method under test is supposed to return null, test for that explicitly. If it isn’t supposed to return null, returning null is an error condition and should be handled as such by your test.
Same with not-null, or indeed anything at all.
1
It depends entirely on your general strategy and workflow of using unit tests.
Strict TDD advocates don’t care very much precisely what happens when a unit test fails. A NullPointerException is as good as a AccountBalanceViolation to them. Some even advocate writing tests that don’t even compile initially, and to treat the compile error as a normal failure that triggers creation of the next bit of business code. All that matters is that the bar is red, and you write code to get it green.
If you are more concerned about readability of test output (perhaps you fear that someone totally else will one day work with the code base, or maybe you are refactoring legacy code that doesn’t have any tests), then it can be worthwhile to make sure that if a unit test fails, it will pinpoint the problem as exactly as possible.
In this case, seeing a null reference problem rather than a failed equality is somewhat less clear. But it isn’t very much less clear; I don’t think it is worth doubling the size of the test. In general, though, it can be.