不能在Espresso测试上使用@Inject,也不能使用模拟Web服务器

问题描述 投票:0回答: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
    }
}

然后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

[我的mockWebServer即使没有指向真正的api调用,也没有指向响应,而是指向我已放置到TestRetrofitModule的那个,这是我必须链接那个mockWebServer和Retrofit。

android kotlin android-espresso dagger-2 dagger
2个回答
1
投票

您发布的设置看起来正确。至于未提供的App,您可能需要将其绑定到组件中,因为现在仅绑定TestApp。因此,您需要替换

fun create(@BindsInstance application: TestApp): TestAppComponent

with

fun create(@BindsInstance application: App): TestAppComponent

0
投票

我假设您有一个扩展了SomeClass的类AbstractBaseTest,并且SomeClass调用DaggerXComponent.create().inject(this)注入其依赖项。不幸的是,这样不会注入AbstractBaseTest中声明的依赖项。

您应该像这样在AbstractBaseTest中创建一个函数:

fun injectDependencies() = DaggerXComponent.create().inject(this)

并且具有SomeClass的构造函数和所有扩展AbstractBaseTest的其他类来调用该方法。

在github上有关于此的讨论,请检查此answer

© www.soinside.com 2019 - 2024. All rights reserved.