I initialize my ViewModel at top level, and as it initializes, it calls its init {}
block, which then calls methods that I stub in @Before block.
Although all the tests are passed, NullPointerExceptions is thrown in methods that I call in init {}
. I tried to lateinit
my ViewModel
in @Before
block. It didn't work.
// 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
}