我正在为Kotlin项目编写JUnit测试。我还在我的项目中使用Dagger和AAPT,因此如下所示,ViewModel类附带了Application类依赖项:
应用程序类:
class BaseApplication : Application() {
private lateinit var component: AppComponent
companion object {
lateinit var instance: BaseApplication
private set
}
override fun onCreate() {
super.onCreate()
instance = this
component = DaggerAppComponent.builder()
.databaseModule(DatabaseModule(this))
.connectivityModule(ConnectivityModule(this)).build()
}
}
ViewModel:
abstract class BaseViewModel : ViewModel() {
@Inject
lateinit var connectivityManager: ConnectivityManager
private val injector: AppComponent = DaggerAppComponent
.builder()
.networkModule(NetworkModule)
.databaseModule(DatabaseModule(BaseApplication.instance))
.connectivityModule(ConnectivityModule(BaseApplication.instance))
.build()
init {
inject()
}
private fun inject() {
when (this) {
is ChildListViewModel -> injector.inject(this)
}
}
fun isNetworkConnected(): Boolean {
return if (connectivityManager is ConnectivityManager) {
val networkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo
networkInfo?.isConnected ?: false
} else false
}
}
在我的测试类中,当我尝试初始化ViewModel类时,它会抛出错误:
UninitializedException lateinit var尚未初始化。
答案 0 :(得分:0)
您是否要初始化BaseViewModel,因为在您显示的代码中我将该类视为抽象的吗? ViewModel具有生命周期意识,应从活动本身内部实例化。