I have a View Model
that extends AndroidViewModel
class MoveViewModel(application: Application): AndroidViewModel(application),CoroutineScope{
....
}
And I want to unit test it but I cannot figure out how to Mock the Application class
@Test
fun testSearchDataValidation() {
val application = Mockito.mock(Application::class.java)
val viewModel = MoveViewModel(application)
.....
}
But when I go to run the test I get an error that Mockito
cannot mock Application
org.mockito.exceptions.base.MockitoException: Mockito cannot mock this class: class android.app.Application.
Mockito can only mock non-private & non-final classes.
How do I mock the Application class to pass it to my view model?
Edit:
Here is my folder hierarchy as suggested by @farhanjk
What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.
Writing tests for ApiService So, configure the mockWebserver on the @before function. On the test case mock the API call result into mockWebServer response and call the API call method. And then verify the request-response and expected response using the assertEqual function. That's it.
You will useAndroid studio to create an Android application under a package com. tutorialspoint.
Mockito.mock(Application::class.java)
In your test
folder, create a hierarchy like following:
In the org.mockito.plugins.MockMaker
file, just put a one-liner text mock-maker-inline
.
Mock the unmockable: opt-in mocking of final classes/methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With