104
votes

So I started writing tests for our Java-Spring-project.

What I use is JUnit and Mockito. It's said, that when I use the when()...thenReturn() option I can mock services, without simulating them or so. So what I want to do is, to set:

when(classIwantToTest.object.get().methodWhichReturnsAList(input))thenReturn(ListcreatedInsideTheTestClass)  

But no matter which when-clause I do, I always get a NullpointerException, which of course makes sense, because input is null.

Also when I try to mock another method from an object:

when(object.method()).thenReturn(true)

There I also get a Nullpointer, because the method needs a variable, which isn't set.

But I want to use when()..thenReturn() to get around creating this variable and so on. I just want to make sure, that if any class calls this method, then no matter what, just return true or the list above.

Is it a basically misunderstanding from my side, or is there something else wrong?

Code:

public class classIWantToTest implements classIWantToTestFacade{
        @Autowired
        private SomeService myService;

        @Override
        public Optional<OutputData> getInformations(final InputData inputData) {
            final Optional<OutputData> data = myService.getListWithData(inputData);
            if (data.isPresent()) {
                final List<ItemData> allData = data.get().getItemDatas();
                    //do something with the data and allData
                return data;
            }

            return Optional.absent();
        }   
}

And here is my test class:

public class Test {

    private InputData inputdata;

    private ClassUnderTest classUnderTest;

    final List<ItemData> allData = new ArrayList<ItemData>();

    @Mock
    private DeliveryItemData item1;

    @Mock
    private DeliveryItemData item2;



    @Mock
    private SomeService myService;


    @Before
    public void setUp() throws Exception {
        classUnderTest = new ClassUnderTest();
        myService = mock(myService.class); 
        classUnderTest.setService(myService);
        item1 = mock(DeliveryItemData.class);
        item2 = mock(DeliveryItemData.class);

    }


    @Test
    public void test_sort() {
        createData();
        when(myService.getListWithData(inputdata).get().getItemDatas());

        when(item1.hasSomething()).thenReturn(true);
        when(item2.hasSomething()).thenReturn(false);

    }

    public void createData() {
        item1.setSomeValue("val");
        item2.setSomeOtherValue("test");

        item2.setSomeValue("val");
        item2.setSomeOtherValue("value");

        allData.add(item1);
        allData.add(item2);


}
20
the object in when() must be a mock created by Mockito.mock(), it does not work for manually created real objects - not sure if that's your issue, since I'm not really getting where your problem is...Nadir
Please post some code.Michael Lloyd Lee mlk
It sounds like classIwantToTest.object.get() result is not a mock, or that get() is returning null. But please post your code, showing your test, and initialization of your mocks.vikingsteve
Added some code. Needed to change the variable-names, since it's from my company ;).user5417542
refer my answer belowanand krish

20 Answers

71
votes

The default return value of methods you haven't stubbed yet is false for boolean methods, an empty collection or map for methods returning collections or maps and null otherwise.

This also applies to method calls within when(...). In you're example when(myService.getListWithData(inputData).get()) will cause a NullPointerException because myService.getListWithData(inputData) is null - it has not been stubbed before.

One option is create mocks for all intermediate return values and stub them before use. For example:

ListWithData listWithData = mock(ListWithData.class);
when(listWithData.get()).thenReturn(item1);
when(myService.getListWithData()).thenReturn(listWithData);

Or alternatively, you can specify a different default answer when creating a mock, to make methods return a new mock instead of null: RETURNS_DEEP_STUBS

SomeService myService = mock(SomeService.class, Mockito.RETURNS_DEEP_STUBS);
when(myService.getListWithData().get()).thenReturn(item1);

You should read the Javadoc of Mockito.RETURNS_DEEP_STUBS which explains this in more detail and also has some warnings about its usage.

I hope this helps. Just note that your example code seems to have more issues, such as missing assert or verify statements and calling setters on mocks (which does not have any effect).

211
votes

I had this issue and my problem was that I was calling my method with any() instead of anyInt(). So I had:

doAnswer(...).with(myMockObject).thisFuncTakesAnInt(any())

and I had to change it to:

doAnswer(...).with(myMockObject).thisFuncTakesAnInt(anyInt())

I have no idea why that produced a NullPointerException. Maybe this will help the next poor soul.

57
votes

I had the same problem and my issue was simply that I had not annotated the class properly using @RunWith. In your example, make sure that you have:

@RunWith(MockitoJUnitRunner.class)
public class Test {
...

Once I did that, the NullPointerExceptions disappeared.

25
votes

For future readers, another cause for NPE when using mocks is forgetting to initialize the mocks like so:

@Mock
SomeMock someMock;

@InjectMocks
SomeService someService;

@Before
public void setup(){
    MockitoAnnotations.initMocks(this); //without this you will get NPE
}

@Test
public void someTest(){
    Mockito.when(someMock.someMethod()).thenReturn("some result");
   // ...
}

Also make sure you are using JUnit for all annotations. I once accidently created a test with @Test from testNG so the @Before didn't work with it (in testNG the annotation is @BeforeTest)

20
votes

For me the reason I was getting NPE is that I was using Mockito.any() when mocking primitives. I found that by switching to using the correct variant from mockito gets rid of the errors.

For example, to mock a function that takes a primitive long as parameter, instead of using any(), you should be more specific and replace that with any(Long.class) or Mockito.anyLong().

Hope that helps someone.

11
votes

Make sure you initialize your mocks.

JUnit4 use @Before

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

JUnit5 use @BeforeEach

@BeforeEach
public void setup() {
    MockitoAnnotations.initMocks(this);
}

For JUnit5 check, you are using proper imports also.

import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
6
votes

Corner case:
If you're using Scala and you try to create an any matcher on a value class, you'll get an unhelpful NPE.

So given case class ValueClass(value: Int) extends AnyVal, what you want to do is ValueClass(anyInt) instead of any[ValueClass]

when(mock.someMethod(ValueClass(anyInt))).thenAnswer {
   ...
   val v  = ValueClass(invocation.getArguments()(0).asInstanceOf[Int])
   ...
}

This other SO question is more specifically about that, but you'd miss it when you don't know the issue is with value classes.

4
votes

you need to initialize MockitoAnnotations.initMocks(this) method has to called to initialize annotated fields.

   @Before public void initMocks() {
       MockitoAnnotations.initMocks(this);
   }

for more details see Doc

3
votes

As this is the closest I found to the issue I had, it's the first result that comes up and I didn't find an appropriate answer, I'll post the solution here for any future poor souls:

any() doesn't work where mocked class method uses a primitive parameter.

 public Boolean getResult(String identifier, boolean switch)

The above will produce the same exact issue as OP.

Solution, just wrap it:

 public Boolean getResult(String identifier, Boolean switch)

The latter solves the NPE.

1
votes

In my case, I missed add first

PowerMockito.spy(ClassWhichNeedToBeStaticMocked.class);

so this can be helpful to somebody who see such error

java.lang.NullPointerException
    at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.addAnswersForStubbing(PowerMockitoStubberImpl.java:67)
    at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:42)
    at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:112)
1
votes
@RunWith(MockitoJUnitRunner.class) //(OR) PowerMockRunner.class

@PrepareForTest({UpdateUtil.class,Log.class,SharedPreferences.class,SharedPreferences.Editor.class})
public class InstallationTest extends TestCase{

@Mock
Context mockContext;
@Mock
SharedPreferences mSharedPreferences;
@Mock
SharedPreferences.Editor mSharedPreferenceEdtor;

@Before
public void setUp() throws Exception
{
//        mockContext = Mockito.mock(Context.class);
//        mSharedPreferences = Mockito.mock(SharedPreferences.class);
//        mSharedPreferenceEdtor = Mockito.mock(SharedPreferences.Editor.class);
    when(mockContext.getSharedPreferences(Mockito.anyString(),Mockito.anyInt())).thenReturn(mSharedPreferences);
    when(mSharedPreferences.edit()).thenReturn(mSharedPreferenceEdtor);
    when(mSharedPreferenceEdtor.remove(Mockito.anyString())).thenReturn(mSharedPreferenceEdtor);
    when(mSharedPreferenceEdtor.putString(Mockito.anyString(),Mockito.anyString())).thenReturn(mSharedPreferenceEdtor);
}

@Test
public void deletePreferencesTest() throws Exception {

 }
}

All the above commented codes are not required { mockContext = Mockito.mock(Context.class); }, if you use @Mock Annotation to Context mockContext;

@Mock 
Context mockContext; 

But it will work if you use @RunWith(MockitoJUnitRunner.class) only. As per Mockito you can create mock object by either using @Mock or Mockito.mock(Context.class); ,

I got NullpointerException because of using @RunWith(PowerMockRunner.class), instead of that I changed to @RunWith(MockitoJUnitRunner.class) it works fine

1
votes

Another common gotcha is that the method signature is accidentally declared as 'final'.

This one catches out a lot of people who work on codebases which are subjected to Checkstyle and have internalised the need to mark members as final.

i.e. in the OP's example:

object.method()

Make sure that method() is not declared as final:

public final Object method() {
}

Mockito cannot mock a final method and this will come up as a wrapped NPE:

Suppressed: org.mockito.exceptions.misusing.InvalidUseOfMatchersException:

Buried deep in the error message is the following:

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
1
votes

For JUnit 5 the test class has to be annotated with:

@ExtendWith(MockitoExtension.class)

imports:

import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;

My issue was fixed with this addition.

0
votes

faced the same issue, the solution that worked for me:

Instead of mocking the service interface, I used @InjectMocks to mock the service implementation:

@InjectMocks
private exampleServiceImpl exampleServiceMock;

instead of :

@Mock
private exampleService exampleServiceMock;
0
votes

Ed Webb's answer helped in my case. And instead, you can also try add

  @Rule public Mocks mocks = new Mocks(this);

if you @RunWith(JUnit4.class).

0
votes

None of these answers worked for me. This answer doesn't solve OP's issue but since this post is the only one that shows up on googling this issue, I'm sharing my answer here.

I came across this issue while writing unit tests for Android. The issue was that the activity that I was testing extended AppCompatActivity instead of Activity. To fix this, I was able to just replace AppCompatActivity with Activity since I didn't really need it. This might not be a viable solution for everyone, but hopefully knowing the root cause will help someone.

0
votes

None of the above answers helped me. I was struggling to understand why code works in Java but not in Kotlin.

Then I figured it out from this thread.

You have to make class and member functions open, otherwise NPE was being thrown.

After making function open tests started to pass.

You might as well consider using compiler's "all-open" plugin:

Kotlin has classes and their members final by default, which makes it inconvenient to use frameworks and libraries such as Spring AOP that require classes to be open. The all-open compiler plugin adapts Kotlin to the requirements of those frameworks and makes classes annotated with a specific annotation and their members open without the explicit open keyword.

0
votes

When using JUnit 5 or above. You have to inject the class annotated with @Mock in an @BeforeEach setup.

0
votes

In my case it was due to wrong import of the @Test annotation

Make sure you are using the following import

import org.junit.jupiter.api.Test;
0
votes

Annotate the test class with: @ExtendWith(MockitoExtension.class).