(Dagger-Android)不能在Espresso测试上使用@Inject,也不能使用mock WebServer

原学程将引见(Dagger-Android)不克不及在Espresso尝试上应用@Inject,也不克不及应用mock WebServer的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

(Dagger-Android)不能在Espresso测试上使用@Inject,也不能使用mock WebServer 教程 第1张

成绩描写

我正在测验考试创立Espresso尝试,并应用mockWebServer,成绩是当我测验考试创立mockWebServer时,它会挪用现实的API挪用,我想截获它并模仿呼应。

我的匕尾组织是:

我的运用法式

open class App : Application(), HasAndroidInjector {

 lateinit var application: Application

 @Inject
 lateinit var androidInjector: DispatchingAndroidInjector<Any>

 override fun androidInjector(): AndroidInjector<Any> = androidInjector

 override fun onCreate() {
  super.onCreate()
  DaggerAppComponent.factory()
.create(this)
.inject(this)
  this.application = this
 }
}

而后是MyAppComponent

@Singleton
@Component(
 modules = [
  AndroidInjectionModule::class,
  AppModule::class,
  RetrofitModule::class,
  RoomModule::class,
  AppFeaturesModule::class
 ]
)
interface AppComponent : AndroidInjector<App> {

 @Component.Factory
 interface Factory {
  fun create(@BindsInstance application: App): AppComponent
 }
}

而后我曾经创立了此TestApp

class TestApp : App() {

 override fun androidInjector(): AndroidInjector<Any> = androidInjector

 override fun onCreate() {
  DaggerTestAppComponent.factory()
.create(this)
.inject(this)
 }
}

这是我的TestAppComponent

@Singleton
@Component(
 modules = [
  AndroidInjectionModule::class,
  AppModule::class,
  TestRetrofitModule::class,
  AppFeaturesModule::class,
  RoomModule::class]
)
interface TestAppComponent : AppComponent {
 @Component.Factory
 interface Factory {
  fun create(@BindsInstance application: App): TestAppComponent
 }
}

留意:在这里我创立了1个名为TestRetrofitModule的新模块,个中base_url是"http://localhost:8080",我没有晓得我能否须要其余实质。

我借创立了TestRunner

class TestRunner : AndroidJUnitRunner() {

 override fun newApplication(
  cl: ClassLoader?,
  className: String?,
  context: Context?
 ): Application {
  return super.newApplication(cl, TestApp::class.java.name, context)
 }

}

并将其搁在testInstrumentationRunner

成绩%一

我没法应用

@Inject
lateinit var okHttpClient: OkHttpClient

由于它显示它未初初化。

成绩二(已处理,感激Skizo)

我的mock WebServer乃至出有分配呼应-虽然没有是指向真实的API挪用,而是指向我搁进的TestRetrofit模块,成绩是我必需将该mock WebServer以及Retrofit链交起去。

推举谜底

比来mockWebServer我碰到了异样的成绩,您须要做的便是搁置1个断面,瞅瞅有甚么毛病,在我的例子中,我把它搁在我正在停止挪用的BaseRepository地位,发明异常是:

java.net.UnknownServiceException: CLEARTEXT co妹妹unication to localhost not permitted by network security policy

我处理这个成绩的办法是将这个添减到我的manifest.xml

android:usesCleartextTraffic="true"

但是您能够必需应用您不妨检查的其余办法android⑻-cleartext-http-traffic-not-permitted。

佳了闭于(Dagger-Android)不克不及在Espresso尝试上应用@Inject,也不克不及应用mock WebServer的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。