Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 834
tyczj Avatar asked Apr 09 '19 18:04

tyczj


People also ask

How do you mock an object in unit testing?

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.

How do you write test cases for MVVM?

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.

Which package do we need to use for writing Android test cases?

You will useAndroid studio to create an Android application under a package com. tutorialspoint.


Video Answer


1 Answers

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

like image 178
farhanjk Avatar answered Nov 15 '22 08:11

farhanjk