1

I am trying to mock data with Mockito and getting NPE. Here is the sample code I am trying to test:

public class MyPresenter implements Contract.Presenter { @Inject MyManager myManager; @Override public void doSomething(Data data) { myManager.doSomething(data); } } public class MyPresenterTest { @Mock private MyManager myManager; @InjectMocks private MyPresenter myPresenter; @Before public void setup(){ MockitoAnnotations.initMocks(this); } @Test public void doSomethingTest(){ Data data = new Data(); myPresenter.doSomething(data); verify(myManager).doSomething(data); } }

NPE is coming at the following line in the MyPresenter class.

myManager.doSomething(data);

@Inject in MyPresenter injects the object using Dagger 2.

Could anyone please help ?

3
  • You have not added the Dagger component which injects these dependencies. Commented Feb 27, 2019 at 7:52
  • Will that not be handled by Mockito ? What I am expecting is Mockito will create mock objects and inject it into my presenter class with annotation @InjectMocks. And that object should be enough to test the calls to its methods. Is my understanding wrong ? Commented Feb 27, 2019 at 7:55
  • check the answer below. Commented Feb 27, 2019 at 8:01

1 Answer 1

2

Mockito injects mocks only to the constructor, leaving the fields undefined. In order to test it properly, one needs to initialize the class with the constructor parameter and Mockito by hand. It will work if you can add a constructor which takes in MyManager instance such as -

public class MyPresenter implements Contract.Presenter { @Inject MyManager myManager; public MyPresenter(MyManager myManager){ // constructor is required for mocikto to inject your fields. this.myManager = manager } @Override public void doSomething(Data data) { myManager.doSomething(data); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That makes sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.