0

I have the following code:

RoomCell r = b.GetRoomCellAt(1, 2);
assertTrue(r.isDoorway());

The second line is failing with a null pointer exception, as if r hadn't been instantiated. But I'm setting it equal to a cell that that method retrieves, so it is obviously not null.

Why would I possibly be getting this error?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
OpenSrcFTW
  • 201
  • 5
  • 14

4 Answers4

3

What's your full stacktrace? It is needed in order to determine which of the following is the cause:

It's possible that GetRoomCellAt doesn't find a value and returns null

It's possible that the implementation of GetRoomCellAt accesses a null pointer

It's possible that the implementation of isDoorway accesses a null pointer

FYI, it is good practice to use the @Nullable annotation to annotate parameters and return types

Uri
  • 88,451
  • 51
  • 221
  • 321
  • +1 for making me read about the `@Nullable` annotation. A quick Google search led me to http://stackoverflow.com/questions/14076296/nullable-annotation-usage :) – icedwater Oct 03 '13 at 04:03
  • If you use Eclipse, you now get built in Nullability analysis (though you may have to turn it on). That being said, I often find Guava's Optional to be more effective. – Uri Oct 03 '13 at 05:05
2

The function GetRoomCellAt() can probably still return NULL.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
0
if(r != null)
{
  assertTrue(r.isDoorway());
}

instead of

assertTrue(r.isDoorway());


b.GetRoomCellAt(1, 2); 

This cell may be null. So only you are getting nullPointerException

newuser
  • 8,338
  • 2
  • 25
  • 33
0

The only way you'd be getting a NullPointerException is if r was indeed null. You can put this in your test conditions to ensure that, if r actually is null, then the test will fail:

RoomCell r = b.GetRoomCellAt(1, 2);
assertNotNull(r);
assertTrue(r.isDoorway());

If r is null, then the test fails early, and you avoid the NPE.

Makoto
  • 104,088
  • 27
  • 192
  • 230