assume you have a unit test that contains these lines
assertNotNull(someVal);
assertNotEmpty(someVal);
This obviously checks that someVal is not null and is populated with something.
The question is, is the first line necessary and does it add anything to the test? Should we not just have the second line, and if it’s null it will throw a null pointer exception which still indicates a failing unit test (but not a failing assertion).
What’s the best practice in such simple cases?
I’m not a big fan of
assertNot()‘s and more generally testing unexpected things that could happen to the SUT, let alone testing them in addition to the normal Assert in every single test.IMO you should only test for nominal states of your objects. If it is normal for
someValto be null in some circumstances, then create a dedicated test method checking that it is indeed null in that scenario. Choose an intention-revealing name for your test, likesomeValShouldBeNullWhen...(). Do the same for empty, or any other value.You see that unexpected things happen to your SUTs by looking at your tests exception messages, not by trying to forecast each of these unexpected things in advance and cramming your tests with assertNots for them.