Espresso Injecting a Mock Presenter Object

2020-07-10 07:19发布

问题:

I'm trying to known better the espresso framework for testing in android, however I'm having a problem trying to mock my presenter.

First of all I'm using some adapted MVP architecture on my application, Therefore, I'm using something like View (Activity) -> Presenter -> Model -> Presenter -> View, to make a request and update the UI.

My activity once created will make a request in order to update all the UI and once the result is received updates the UI accordingly.

public class MyActivity extends AppCompatActivity implements IPresenter{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);

        new Presenter().doRequestToUpdateUI();
    }

    @Override
    public void onResponseReceived(UIObject uiOject){
       findViewById(R.id.button).setVisibility(uiOject.getVisibility());
    }
}

However, this doRequestToUpdateUI() needs some previous authentication and therefore the hole presenter needs to be mocked, in order to test other UI on my activity.

Is there a way to mock my presenter and inject it to the activity, or at least do nothing when the method doRequestToUpdateUI() is called.

I'm doing my test like this, but until now is not working.

@LargeTest
@RunWith(AndroidJUnit4.class)
public class MyActivityInstrumentationTest {

    @Mock
    public Presenter presenter;

    @InjectMocks
    public PresenterMock mPresenterMock;

    @Rule
    public ActivityTestRule<MyActivity> mActivityTestRule = new ActivityTestRule<MyActivity>(MyActivity.class, true, false) {
        @Override
        protected void beforeActivityLaunched() {
            presenter = Mockito.mock(Presenter.class);
            Mockito.doNothing().when(presenter).doRequestToUpdateUI();
            super.beforeActivityLaunched();
        }
    };

    @Test
    public void simpleTestCheck() {
        mActivityTestRule.launchActivity(new Intent());

       //here I should call the onResponseReceived() with a mock object however the presenter is not being injected
       widthId(R.id.button).matches(isDisplayed());
    }
 }