I have been trying this for a week. And I have crawled every article available but their implementations or examples fall short or stop at the steps of Espresso Tests.
My Android Application follows MVP architecture (And is in Java)
Scenario: [Giving just one example]
I have a HomeActivity
which gets a HomePresenter
using Dagger2. (Provides method in the HomeModule
exposed through a void inject(HomeActivity activity)
in the HomeComponent
.
In my espressoTest for HomeActivity
I would like to inject a mockpresent.
I Have not exposed this dependencies inside an AppModule
through an AppComponent
. which most examples on the net do (So they just create a new testApplication and then do the needfull)
I do not want to use the productFlavours way of injecting or providing mockclasses as it doesnt give me control over the Mockito.when
methods.
So basically. I would like to inject a mockpresenter wherein i can do whatever Mockito.when()
s on it for the sake of my unit tests in espresso.
My Code is below.
HomeComponent
@HomeScope
@Component(modules = HomeModule.class,dependencies = AppComponent.class)
public interface HomeComponent {
void inject(HomeActivity activity);
}
HomeModule
@Module
public class HomeModule {
private final IHomeContract.View view;
public HomeModule(IHomeContract.View view) {
this.view = view;
}
@Provides
@HomeScope
public IHomeContract.Presenter presenter(FlowsRepository flowsRepository, UserRepository userRepository, LoanRepository loanRepository) {
return new HomePresenter(view, flowsRepository, userRepository, loanRepository);
}
}
AppComponent
@Component(modules = {AppModule.class,RepositoryModule.class})
@AppScope
public interface AppComponent {
void inject(App app);
FlowsRepository flowRepository();
LoanRepository loanRepository();
UserRepository userRepository();
}
AppModule
@Module
public class AppModule {
private Context appContext;
public AppModule(@NonNull Context context) {
this.appContext = context;
}
@Provides
@AppScope
public Context context() {
return appContext;
}
}
App
component = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
component.inject(this);
HomeActivity
HomeComponent component = DaggerHomeComponent.builder()
.appComponent(((App) getApplication()).getComponent())
.homeModule(new HomeModule(this))
.build();
Once again. In my tests (espresso) i would like to inject a mockedHomePresenter the set by Mockito. So I can just unit test my views.