Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

considering NullPointerException as a unit test failure: is it good practice?

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?

like image 250
Ashkan Aryan Avatar asked Oct 25 '12 12:10

Ashkan Aryan


People also ask

Is it good practice to throw NullPointerException?

It is generally a bad practice to catch NullPointerException.

When should we throw a 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.

Why NullPointerException should not be caught?

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.

Why NullPointerException occurs in junit test case?

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.


1 Answers

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");

like image 66
pengibot Avatar answered Nov 02 '22 23:11

pengibot