tyczj
tyczj

Reputation: 73731

How to mock Application class to unit test ViewModel

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

Upvotes: 9

Views: 8584

Answers (1)

farhanjk
farhanjk

Reputation: 1762

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

Upvotes: 13

Related Questions