I am testing a class that has a private method "getEntityManager". This method returns an entity manager instance to be used in the public method "getAllProducts". So I use PowerMockRunner; My dependencies are:
junit-4.1.2
mockito-all-1.10.19
powermock-module-junit4- 1.6.5
powermock-api-mockito-1.6.5
javassist-3.12.1.GA
Hier is my (@GhostCat enhanced) Code:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ProduktDB.class)
public class ProduktDBTest {
static final String PRODUCTID= "id";
List<Product> productList;
EntityManager emmock;
Query q;
@Before
public void setUp() throws Exception {
basicProductList= new ArrayList<>();
BasicProductDao basicProductDao= new BasicProductDao();
basicProductDao.setId(PRODUCTID);
basicProductList.add(basicProductDao);
emmock= mock(EntityManager.class);
q= mock(Query.class);
}
@Test
public void getAllProducts() throws Exception {
when(emmock.createQuery(anyString())).thenReturn(q);
when(q.getResultList()).thenReturn(productList);
ProduktDB spied= spy(new ProduktDB());
/* ***********this is the line with the error:****** */
PowerMockito.doReturn(emmock).when(spied, "getEntityManager");
assertEquals(spied.getAllProducts().get(0).getId(),PRODUCTID );
}
}
However I am getting following error when I want to add the return value on call to the private method:
java.lang.NullPointerException
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.addAnswersForStubbing(PowerMockitoStubberImpl.java:68)
Now I change the critical line to the following:
PowerMockito.when(spied, "getEntityManager").thenReturn(emmock);
No I get another error but it is harmless (see solution bellow). :)