NullPointerException when Mocking?

Kiran Biliyawala
2 min readAug 6, 2020

--

Basic mistakes while mocking…

You might get NullPointerException exception when you try to mock object in your tests. This article is a short list of 3 most common reasons why this might be happening.

Here is a working example of FooRepositoryTest class for reference:

@RunWith(MockitoJUnitRunner.class)
public final class FooRepositoryTest {

@Mock
private FooRepository fooRepository;

@Test
public void testBar() {
val color = new String("white");
Mockito.when(this.fooRepository.getColor()).thenReturn(color);
val result = this.fooRepository.getColor();
Assert.assertThat(result, is(new String("white"));
}
}

FooRepositoryTest class is mocking fooRepository object.

So you are running your test and suddenly you see NullPointerException!!

java.lang.NullPointerException at com.your.custom.clazz.Method.insertTest(SomeServiceTest.java:20)

You looked it up and it seems your test is written correctly. So what might be a problem if you know how to mocking works?

If you are sure by your mocking skills, the issue will be probably somewhere else. And most likely very trivial. Here is a list of 3 things you should check out.

1. You messed up while returning
Most likely you mistyped returning function. You probably wanted to return the value for the mocked object. So probably instead of when-thenReturn , you might have typed just when-then, or maybe it was IntelliSense, maybe you did it purposely. But definitely, NullPointerException happened because you want something which is not there. Check if you are returning correctly.

2. Specify Mockito running class
Don’t forget to annotate your Testing class with @RunWith(MockitoJUnitRunner.class)or MockitoAnnotations.initMocks(this) in method before mocking using when. Most of the people just forget to specify the test runner, running class for mocking — the most common mistake I’ve observed in my career.

3. Annotate the mocking object with the @Mock annotation
If you want to mock object you need to definitely annotated the object with @Mock annotation or Mockito.mock(Foo.class) while creating object to be mocked.

--

--