首页 > 解决方案 > AppContainer vs Singleton - 哪一个可以简化 Android 中的测试?

问题描述

我实际上是在探索 Android 中的依赖注入(DI)。在探索使手动DI 与自动DI相比变得困难的原因时,我尝试实现手动DI的Android 文档中给出的示例。

在我上面提到的文档中,提到了Singleton,它会使代码难以测试,因为测试将连接到同一个地方。

而且,为了克服这个问题,他们尝试使用AppContainer来全局访问对象。下面是他们提到的 AppContainer 类。

// Container of objects shared across the whole app
class AppContainer {

    // Since you want to expose userRepository out of the container, you need to satisfy
    // its dependencies as you did before
    private val retrofit = Retrofit.Builder()
                            .baseUrl("https://example.com")
                            .build()
                            .create(LoginService::class.java)

    private val remoteDataSource = UserRemoteDataSource(retrofit)
    private val localDataSource = UserLocalDataSource()

    // userRepository is not private; it'll be exposed
    val userRepository = UserRepository(localDataSource, remoteDataSource)
}

AppContainer的实例在Application类中创建一次。并且,通过 Application 类,它在整个应用程序中公开UserRepository 。

来回答我的问题, AppContainer如何在像 Singleton 那样保存对象以在应用程序中共享的同时简化测试?

标签: androiddependency-injectionsingletonappcontainer

解决方案


推荐阅读