何模拟Application类以对ViewModel进行单元测试

何模拟Application类以对ViewModel进行单元测试

本文介绍了如何模拟Application类以对ViewModel进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个View Model扩展了AndroidViewModel

class MoveViewModel(application: Application): AndroidViewModel(application),CoroutineScope{
    ....
}

我想对其进行单元测试,但是我无法弄清楚如何模拟Application类

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)

        .....
    }

但是当我去运行测试时,我得到一个错误,提示Mockito无法模拟Application

But when I go to run the test I get an error that Mockito cannot mock Application

Mockito只能嘲笑非私人&非最终课程.

Mockito can only mock non-private & non-final classes.

如何模拟Application类以将其传递给我的视图模型?

How do I mock the Application class to pass it to my view model?

这是@farhanjk建议的文件夹层次结构

Here is my folder hierarchy as suggested by @farhanjk

推荐答案

Mockito.mock(Application::class.java)

在您的test文件夹中,创建如下所示的层次结构:

In your test folder, create a hierarchy like following:

org.mockito.plugins.MockMaker文件中,只需放置一个单行文本mock-maker-inline.

In the org.mockito.plugins.MockMaker file, just put a one-liner text mock-maker-inline.

嘲笑无法嘲笑的人:选择参加最终嘲讽类/方法

这篇关于如何模拟Application类以对ViewModel进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 19:43