(DAGGER-ANDROID) 不能在 Espresso 测试中使用 @Inject 并且不能使用 mockWebServer

Stu*_*DTO 7 android kotlin dagger android-espresso dagger-2

我正在尝试创建 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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后 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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了这个 TestApp

class TestApp : App() {

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

    override fun onCreate() {
        DaggerTestAppComponent.factory()
            .create(this)
            .inject(this)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 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
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:这里我创建了一个新模块,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)
    }

}
Run Code Online (Sandbox Code Playgroud)

并将其放在 testInstrumentationRunner

问题一

我不能用

@Inject
lateinit var okHttpClient: OkHttpClient
Run Code Online (Sandbox Code Playgroud)

因为它说它没有初始化。

问题 2(已解决,感谢 Skizo)

我的 mockWebServer 没有发送响应——尽管没有指向真正的 api 调用,而是指向我已经放到 TestRetrofitModule 的那个,问题是我必须链接那个 mockWebServer 和 Retrofit。

Ski*_*ᴉʞS 2

我最近遇到了同样的问题mockWebServer,您需要做的是放置一个断点并查看错误是什么,在我的例子中,我将其放在我BaseRepository正在调用的位置,发现异常是:

java.net.UnknownServiceException: CLEARTEXT communication to localhost not permitted by network security policy
Run Code Online (Sandbox Code Playgroud)

我为解决问题所做的是将其添加到我的manifest.xml

android:usesCleartextTraffic="true"
Run Code Online (Sandbox Code Playgroud)

但您可能必须使用其他方法,您可以查看android-8-cleartext-http-traffic-not-permissed