Allocated object with Mockito Kotlin method without collapsing
I have the following code:
@RunWith(MockitoJUnitRunner::class)
class OnboardingViewModelTest {
@Mock lateinit var authService : AuthService
lateinit var internetProvider: InternetStatusProvider
private lateinit var viewModel: OnboardingViewModel
@Before
fun setup() {
internetProvider = mock()
whenever(internetProvider.hasInternet()).thenReturn(true)
}
The constructor InternetStatusProvider
looks like this:
InternetStatusProvider(context:Context)
I get NullPointerException
when executing a method internetProvider.hasInternet()
because this method implementation uses the context
one passed in the constructor and the real method is being driven?
What am I missing here? is it all about stubbing out the real implementation of that method?
source to share
Mockito cannot complete final methods. If you try to execute the final method from a crafted instance, the real code will be executed. Since Kotlin functions by default final
, you need to add a modifier open
to the function.
Mockito has an incubation feature that lets you mock final classes and methods, which might be worth a look.
source to share