(Dagger-Android)不能在Espresso测试上使用@Inject,也不能使用mock WebServer [英] (DAGGER-ANDROID) Can not use @Inject on an Espresso Test and can not use mockWebServer

查看:0
本文介绍了(Dagger-Android)不能在Espresso测试上使用@Inject,也不能使用mock WebServer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建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
    }
}

注意:在这里我创建了一个名为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

问题%1

我无法使用

@Inject
lateinit var okHttpClient: OkHttpClient

因为它显示它未初始化。

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

我的mock WebServer甚至没有分派响应-尽管不是指向真正的API调用,而是指向我放入的TestRetrofit模块,问题是我必须将该mock WebServer和Retrofit链接起来。

推荐答案

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

java.net.UnknownServiceException: CLEARTEXT communication to localhost not permitted by network security policy

我解决这个问题的方法是将这个添加到我的manifest.xml

android:usesCleartextTraffic="true"

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

这篇关于(Dagger-Android)不能在Espresso测试上使用@Inject,也不能使用mock WebServer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆