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?
It is generally a bad practice to catch NullPointerException.
NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference. Accessing or modifying an instance field of the object referred by a null reference.
The 'reason' that catching NullPointerException is considered a bad practice is not because you're supposed to let it bubble up when something goes wrong! Saying any exception is 'best left unhandled' based solely on its type seems like a bad idea. A NPE is considered the result of a programming error.
NullPointerException is thrown when program attempts to use an object reference that has the null value. These can be: Invoking a method from a null object.
You shouldn't see a NPE as a test failure. You should actually assert it is not null and provide an error message,
assertNotNull(someVal, "Some descriptive message saying why value should not be null");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With