如何在@Before块之前存根方法



我在顶层初始化ViewModel,当它初始化时,它调用它的init {}块,然后它调用我在@Before块中存根的方法。

尽管所有测试都通过了,但在我在init {}中调用的方法中会抛出NullPointerExceptions。我尝试在@Before块中lateinit我的ViewModel。它不起作用。

// AViewModelTest.kt
private val repoMock: ARepository = mock()
private val viewModel: AViewModel = AViewModel(repoMock)
@Before
fun setup() {
// method stubbing
`when`(repoMock.getSmth()).thenReturn(response)
}

// AViewModel.kt
constructor(repo: ARepository) {}
init {
onStartLoading(repo)
}
fun onStartLoading(repo: ARepository) {
val response = repo.getSmth()
handleResponse(response) // response is null here -> NullPointerException
}

最终,@Before中的lateinit完成了任务。出现此问题是因为我在ViewModel中隐式引用了AndroidContext

最新更新