I have a dao.create() call that I want to mock when testing a method.
But I am missing something as I’m still getting NPE. What is wrong here?
class MyService {
@Inject
private Dao dao;
public void myMethod() {
//..
dao.create(object);
//
}
}
How can I mock out the dao.create() call?
@RunWith(PowerMockRunner.class)
@PrepareForTest(DAO.class)
public void MyServiceTest {
@Test
public void testMyMethod() {
PowerMockito.mock(DAO.class);
MyService service = new MyService();
service.myMethod(); //NPE for dao.create()
}
}
You are not injecting the DAO. With mockito you can change your test class to use @InjectMocks and use mockito runner.
You can read more about InjectMocks at Inject Mocks API
Simpler way is changing your injection to injection by constructor. For example, you would change MyService to
then your test you could simple pass the mocked DAO in setup.
now you can use
verifyto check ifcreatewas called, like:Using injection by constructor will let your dependencies clearer to other developers and it will help when creating tests 🙂