3 basic mistakes for NullPointerException when Mock

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 DocumentRepositoryTest class for reference:

@RunWith(MockitoJUnitRunner.class)
public final claNewDs DocumDTOoryTest {

  @Mock
  private DocumentRepository documentRepository;

  @Test
  public void testConvertToNewDocument() {
    val paperColor = new String("white");
    Mockito.when(this.documentRepository.getPaperColor()).thenReturn(paperColor);
    val color = this.documentRepository.getDocumentColor();
    Assert.assertThat(color, is(new String("white"));
  }
}

DocumentRepositoryTest class is mocking documentRepository object.

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

java.lang.NullPointerException at com.your.custom.clazz.Method.insertTest(CustomServiceTest.java:50)

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. Return something for your Mock.
Most likely you mistyped returning function. You probably wanted to return the value for the mocked object. So instead of when-thenReturn , you might type just when-then. 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 something.

2. Specify Mockito running class
Don’t forget to annotate your Testing class with @RunWith(MockitoJUnitRunner.class). Most of the people just forget to specify the test runner, running class for mocking.

3. You need to annotate the mocking object with the @Mock annotation
If you want to mock object you need to definitely annotated the object with @Mock annotation.

 

This entry was posted in Testing and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.