0

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
}
madim
  • 774
  • 10
  • 22
  • 1
    Could you add some code as well? – tynn Nov 23 '18 at 12:03
  • You could try the @BeforeClass annotation: https://stackoverflow.com/questions/20295578/difference-between-before-beforeclass-beforeeach-and-beforeall – MasterQueue Nov 23 '18 at 12:13
  • 1
    Please read "How to create a [mcve]". Then use the [edit] link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. – GhostCat Nov 23 '18 at 13:27
  • @tynn updated the question – madim Nov 26 '18 at 03:36
  • 1
    `init` blocks are equivalent to constructor bodies, and so they will always be called before any methods. This is expected behavior. `repo` is `null` when `onStartLoading(repo)` is called from `init`. – RussHWolf Nov 26 '18 at 03:37
  • @Brucelet I tried to `lateinit viewModel` in `@Before` block, but it didn't work for some reason. – madim Nov 26 '18 at 03:40
  • The `@Before` block is called after `init`, so initializing in `@Before` doesn't help you here. Probably a better solution is to move the code from the `init` block into the `setup()` function instead. – RussHWolf Nov 26 '18 at 03:46
  • @MasterQueue it didn't work :( – madim Nov 26 '18 at 03:47

1 Answers1

0

In the end, lateinit in @Before did the thing. The problem occurred because I had an implicit reference to Android Context in my ViewModel.

madim
  • 774
  • 10
  • 22