Issue
I have a button in my app and when user clicks i, it displays a Text. Now I want to test it with Espresso
.
The code in MainActivity
is :
public void onButtonGetDataClick(View view) {
mainPresenter.onButtonClick();
}
@Override
public void showData(String data) {
textView.setText(data);
}
and for mainPresenter.onButtonClick()
:
@Override
public void onButtonClick() {
if (dataSource != null) {
mainView.showData(dataSource.getReleaseString());
}
}
where dataSource
is injected to MainPresenter
.
The problem is how I can test such a thing ? I tried mocking dataSource
and test it like :
@Test
public void onButtonGetDataClicked_textViewDisplaysData() {
when(dataSource.getReleaseString()).thenReturn(MOCK_STRING);
activityRule.launchActivity(new Intent());
/** Click Button*/
onView(withId(R.id.btn_get_data))
.perform(click());
onView(withId(R.id.tv_text_data))
.check(matches(withText(MOCK_STRING)));
}
but this is always giving me the "RELEASE_STRING" and not "MOCK_STRING" therefore test always fails
Edit : injection code :
@Before
public void setUp() {
mockMainView = mock(MainMVP.View.class);
mainPresenter = new MainPresenter(mockMainView);
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
MockMyApplication applicationContext
= (MockMyApplication) instrumentation.getTargetContext().getApplicationContext();
MockDataComponent component = (MockDataComponent) applicationContext.component();
component.inject(mainPresenter);
}
and of course I use
@Inject
DataSource dataSource;
MockDataComponent :
@Singleton
@Component(modules = {MockDataModule.class})
public interface MockDataComponent extends DemoComponent {
void inject(MainPresenter mainPresenter);
}
and MockDataModule :
@Module
public class MockDataModule {
@Provides
public DataSource providesDataSource() {
return mock(DataSource.class);
}
}
Solution
You are not setting the presenter for your Activity
here so the mock datasource cannot be accessed.
By making Presenter component allows you to inject presenter for your activity and this singleton presenter can then have the mock datasource to present.
Answered By - Niko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.