2

Why do I get NullPointerException?

Here is my code:

@Stateless
@LocalBean
class SomeDao {

@PersistenceContext(unitName = "some-value")
private EntityManager entityManager;

public EntityManager getEntityManager() {
    return this.entityManager;
}

public long getNextId() {
    long someLongValue = getEntityManager().someMethod();
    //some code
    return someLongValue;
}
}

class SomeTest() {
@Spy
private SomeDao dao = new SomeDao();

@Test
public void someTestMethod() {
    MockitoAnnotations.initMocks(this);
    when(dao.getNextId()).thenReturn(10L);
}
}

When I run the test I get the following exception: java.lang.NullPointerException at com.some.api.some.package.dao.SomeDao.getNextId(SomeDao.java:13) ...

Later I want to add new classes to mock, and the getNextId method will be called inside one of them.

Thank you!

pityo10000
  • 117
  • 1
  • 13

2 Answers2

3

MockitoAnnotations.initMocks(this) should be executed before test method, in JUnit

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

Or in TestNG use @BeforeMethod

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

In above example, initMocks() is called in @Before (JUnit4) method of test's base class.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
1

When you use @Spy, you cannot use when/thenReturn syntax.

You must use doReturn/when syntax.

See also this post: Mockito - difference between doReturn() and when()

So either changing your @Spy to @Mock or changing your stubbing, will solve the problem.

Dimitris
  • 560
  • 3
  • 17