5
votes

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

enter image description here

1
You're trying to mock the Application class in an AndroidTest, that doesn't make much sense since you can get the actual Application instance - lelloman
@lelloman not sure what you mean, I thought that the androidTest was for when you need to work with the android framework, the ViewModel uses some shared preferences. I am very new to unit testing in android so I dont understand everything fully but can I do these tests in the test folder? - tyczj
If you are really unit testing a view model you should be able to do so in test folder, you would need to mock all Android dependencies (like Application or SharedPreferences), tests in androidTest folder instead have your actual application available. You should be able to unit test view models in test, they're much faster than androidTest. - lelloman

1 Answers

8
votes

Mockito.mock(Application::class.java)

In your test folder, create a hierarchy like following:

enter image description here

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