How to mock Application class to unit test ViewModel

最后都变了- 提交于 2020-04-11 05:50:06

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/55599337/how-to-mock-application-class-to-unit-test-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!