lundi 28 janvier 2019

Why I get NullPointerException while mocking?

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!

Aucun commentaire:

Enregistrer un commentaire