简体   繁体   中英

Injecting mocks in a Robolectric test

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM