Android Mockito kotlin.UninitializedPropertyAccessException:lateinit属性dataManager尚未初始化

时间:2018-09-14 15:19:56

标签: android kotlin mockito dagger-2 mvp

我在Mockito测试中不断得到kotlin.UninitializedPropertyAccessException: lateinit property xxx has not been initialized。但是该应用程序正常运行。注意:我不想让主持人加入活动。预先感谢!

这是我的活动:

class CreateAccountActivity : AppCompatActivity(), CreateAccountView {

private var presenter: CreateAccountPresenter? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_create_account)
    presenter = CreateAccountPresenter()
    ((application) as CariumApp).getDaggerComponent().inject(presenter!!)

    presenter?.attachView(this)
}

这是我的主持人:

class CreateAccountPresenter {
private var view: CreateAccountView? = null

@Inject
lateinit var dataManager: DataManager

fun attachView(view: CreateAccountView) {
    this.view = view

    dataManager.getServiceDocuments(true, object : GetServiceDocumentsListener { 
       // ...
    })
}

这是我的DataManager:

interface DataManager {
    fun getServiceDocuments(latest: Boolean, listener: GetServiceDocumentsListener)
}

和AppDataManager:

Singleton
class AppDataManager @Inject constructor(context: Context) : DataManager {
// ...
}

最后我的测试失败了:

class CreateAccountPresenterTest {

val mockDataManager: DataManager = mock()

val mockCreateAccountView: CreateAccountView = mock()

private val createAccountPresenter = CreateAccountPresenter()

@Test
fun getServiceDocuments() {
    doAnswer {
        val args = it.arguments
        (args[1] as GetServiceDocumentsListener).onError()
        null
    }.`when`(mockDataManager).getServiceDocuments(Mockito.anyBoolean(), anyOrNull())

    createAccountPresenter.attachView(mockCreateAccountView)

    verify(mockCreateAccountView).hideLoadingDialog()
}
}

渐变文件:

testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:2.22.0'
testImplementation "org.mockito:mockito-inline:2.22.0"
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.0.0-RC1"
implementation 'com.google.dagger:dagger:2.16'
kapt 'com.google.dagger:dagger-compiler:2.16'

我的模块类:

@Module
open class MyModule(private var context: Context) {

@Provides
open fun provideContext(): Context {
    return context
}

@Provides
@Singleton
internal fun provideDataManager(appDataManager: AppDataManager): DataManager {
    return appDataManager
}
}

实际错误为 kotlin.UninitializedPropertyAccessException:lateinit属性dataManager尚未初始化

2 个答案:

答案 0 :(得分:0)

您在哪里使用DataManager @Provides方法? Dagger可以识别@Inject中的AppDataManager构造函数,但不能将其识别为接口。为Dagger创建模块,该模块是抽象的,并使用@Binds

https://proandroiddev.com/dagger-2-annotations-binds-contributesandroidinjector-a09e6a57758f

答案 1 :(得分:0)

您没有将模拟内容分配给该字段。在您的测试方法中分配它。致电attachView()

之前
createAccountPresenter.dataManager = mockDataManager