Reputation: 3538
I have to build a Robolectric test for a particular Activity
that has a private field (a presenter). In order to inject a mock into that field I used reflection, since the project I'm working on has no Dependency Injection framework.
My test setup is as follows:
MyActivityTest.java
public class ConsumoViewTest {
@Mock
MvpConsumo.Presenter mockPresenter;
private MyActivity view;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ActivityController<MyActivity> activityController =
Robolectric.buildActivity(MyActivity.class);
view = activityController.get();
try {
FieldUtils.writeField(view, "presenter", mockPresenter, true);
} catch (IllegalAccessException e){
//Exception handling
}
activityController.setup();
}
As part of my Activity
setup, it creates and adds a Fragment
and during OnAttach()
the Fragment
calls the getter for the presenter. Now, the thing I can't understand is that the Activity
returns a real presenter instead of the mock I injected. This real presenter eventually calls my real model and my real webservice which is obviously not ideal for testing.
Does anyone now why my mock is being ignored on this scenario?
Upvotes: 4
Views: 848
Reputation: 3538
After writing the question I realized what the problem was. My reflection does work and the presenter is being initialized as a Mock, but I forgot that during Activity.OnCreate()
the presenter is initialized as a real presenter, thus overriding the Mock I had injected previously.
Upvotes: 2