I am using an if statement to try to catch null lists in my apex tests. On a side not, I am not populating my list about 25% of the time, not sure why that is happening? Sometimes test passes, sometimes does not, will take any ideas on that as well. However, this is my issue right now, this is my if statement:


The problem is, I am not making it past my .isEmpty() check, it returns an error:

System.NullPointerException: Attempt to de-reference a null object

Isn't that the whole purpose of the .isEmpty(), to check and see if there is a null list, that way it doesn't throw errors?


Most likely you're declaring the list variable but you're not setting it to an empty list. If you declare a variable without assigning a value to it:

List <String> courseList;

by default it's value is null. So if you try to check .isEmpty() essentially you're running the method on a null value. So null.isEmpty() will throw the exception.

In that case you can either check for null or default the list variable to an empty list:

Option 1:

if (RegCon.courseList != null && !RegCon.courseList.isEmpty())

Option 2:

When declaring the variable (pretending it's a list of Strings), set it to an empty list:

List <String> courseList = new List <String> ();

  • Ah, ok. I had read somewhere that .isEmpty() checks for Null and also checks for a nothing inside the list, so I had that in my mind. That was wrong, I see that now. Thank you very much for putting me back on the right path. Mar 24 '16 at 2:27
  • 1
    That's correct, the method itself checks for both, null values and empty strings inside a list. In your case, your list itself is null :) Mar 24 '16 at 2:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.