java - Mocking an injected field in unit tests -
i have presenter
class uses field injected through dagger, looks this:
public class rsslistpresenter { @inject rssservice rssservice; // <-- injected field public rsslistpresenter() { setupdi(); } private void setupdi() { daggernetworkcomponent.builder() .networkmodule(new networkmodule()) .build() .inject(this); } public void loaditems() { rss rss = rssservice.getrssfeed() // .... } }
everything works fine. now, unit test rsslistpresenter
class. question how provide mock rssservice
presenter?
ofcourse can add new method setrssservice(rssservice rssservice)
presenter , use provide mock unit tests, adding method unit tests not feel right. correct way handle this?
for completeness here module , component declarations:
@singleton @component(modules = networkmodule.class) public interface networkcomponent { void inject(rsslistpresenter presenter); } @module public class networkmodule { @provides retrofit provideretrofit() { // ... } @provides @singleton rssservice providepcworldrssservice(retrofit retrofit) { return retrofit.create(rssservice.class); } }
property injection not easy test. in case, constructor injection better. refactor constructor this:
private final rssservice rssservice; @inject public rsslistpresenter(rssservice rssservice) { this.rssservice = rssservice; }
now can test easily:
//mocks rssservice mockrssservice; //system under test rsslistpresenter rsslistpresenter; @before public void setup() { mockrssservice = mockito.mock(rssservice.class); rsslistpresenter = new rsslistpresenter(mockrssservice); }
you shouldn't using daggernetworkcomponent.inject(this)
inside rsslistpresenter
. instead should configuring dagger when injects members top-level classes (activity
, fragment
, service
) can access object graph , create instance of rsspresenter
.
why put injectors in activity
, service
, not in rsslistpresenter
? these classes instantiated android system , have no choice use injectors.
to clarify, activity
, fragment
etc. ideal injection targets. rsslistpresenter
etc. injected dependencies. need configure dependency injection framework, dagger, can provide correct dependencies inject injection targets.
so need write @provides
method rsslistpresenter
@provides providersslistpresenter(rssservice rssservice) { return new rsslistpresenter(rssservice); }
Comments
Post a Comment