NullPointerException when Mocking?

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:

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(

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.



Software Architect @ CRED

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store