我想为应用程序编写咖啡测试,所以我正在尝试DaggerMock
到模拟一些外部依赖性等外部存储。
我的Dagger
设置由一个ApplicationComponent
组成,该CC_3具有3个模块(DatabAsemodule,datamodule和ApplicationModule),对于屏幕(Fragment
),我想测试我也有另一个组件,该组件取决于ApplicationComponent
。
到目前为止我尝试过的是:
@Rule public DaggerMockRule<ApplicationComponent> daggerRule =
new DaggerMockRule<>(ApplicationComponent.class, new DatabaseModule(), new DataModule(application),
new ApplicationModule(application)).set(
component -> {
MyApplication app =
(MyApplication) InstrumentationRegistry.getInstrumentation()
.getTargetContext()
.getApplicationContext();
app.setComponent(component);
});
@Rule
public final DaggerMockRule<FeedComponent> rule = new DaggerMockRule<>(
FeedComponent.class, new FeedDataSourceModule(),
new FeedDownloadImageUseCaseModule(), new FeedServiceModule(), new FeedPresenterModule(null))
.addComponentDependency(ApplicationComponent.class, new DatabaseModule(), new DataModule(application), new ApplicationModule(application))
.set(component -> localDataSource = component.localDataSource());
@Mock FeedDao feedDao;
@Mock NetworkUtils networkUtils;
@Mock FeedLocalDataSource localDataSource;
其中localDataSource
实际上是我要模拟的依赖性,并且它是在FeedDataSourceModule
中构建的:
@Module
public class FeedDataSourceModule {
@Provides
@FragmentScope
public FeedItemMapper providesFeedItemMapper() {
return new FeedItemMapper();
}
@Provides
@FragmentScope
public FeedLocalDataSource providesFeedLocalDataSource(FeedDao feedDao, FeedRequestDetailsDao detailsDao, FeedItemMapper mapper) {
return new FeedLocalDataSourceImpl(feedDao, detailsDao, mapper);
}
@Provides
@FragmentScope
public FeedRemoteDataSource providesFeedRemoteDataSource(FeedService feedService, FlagStateService flagStateService,
@Named("Api-Token") String apiToken, @Named("Screen-Size") String screenSize,
@Named("Account-Id") String accountId) {
return new FeedRemoteDataSourceImpl(feedService, flagStateService, apiToken, screenSize, accountId);
}
}
以及具有依赖性ApplicationComponent
的FeedComponent
:
@FragmentScope
@Component( dependencies = ApplicationComponent.class,
modules = {
FeedPresenterModule.class,
FeedServiceModule.class,
FeedDataSourceModule.class,
FeedDownloadImageUseCaseModule.class})
public interface FeedComponent {
@Named("Api-Token") String getApiToken();
@Named("Api-Key") String getApiKey();
FeedLocalDataSource localDataSource();
FeedRemoteDataSource remoteDataSource();
void inject(FeedFragment feedFragment);
}
使用上面发布的两个@Rules
,我可以确认NetworkUtils
确实确实被正确模拟了,因为我已经使用Mockito.when()
返回false
值,并且通过使用我的代码中的断点,我可以看到该值始终是false:
when(networkUtils.isOnline())
.thenReturn(false);
但是,对于localDataSource
而言,这是不正确的,当我宣布:
when(localDataSource.getFeedSorted())
.thenReturn(Flowable.just(feedList));
以防万一它有所帮助,这就是我从 FeedComponent
注入依赖项的方式:
DaggerFeedComponent.builder()
.applicationComponent(MyApplication.getApplicationComponent())
.feedPresenterModule(new FeedPresenterModule(this))
.build()
.inject(this);
为什么在测试中使用两个daggermock规则?我认为您可以在此示例中使用单个规则。