Android体系结构组件ViewModel-如何在测试Activity上模拟ViewModel? [英] Android Architecture Component ViewModel - How to mock ViewModel on test Activity?

查看:129
本文介绍了Android体系结构组件ViewModel-如何在测试Activity上模拟ViewModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试设置类似于 GithubBrowserSample 的UI测试,并且该示例项目似乎仅对Fragment进行了模拟ViewModel,但没有针对Activity的示例.

I'm trying to setup UI testing similar to GithubBrowserSample and it looks like the sample project only has mock ViewModel for Fragment but not an example for Activity.

这是我的代码,我在这里尝试通过模拟ViewModel来测试Activity.但是ViewModel不会在Activity中的onCreate()之前设置.

Here's my code where I am trying to test the Activity by mocking ViewModel. But the ViewModel is not getting set before onCreate() in Activity.

@RunWith(AndroidJUnit4::class)
class MainActivityTest {

    val viewModel = mock(MainViewModel::class.java)

    @Rule
    @JvmField
    val activityRule = ActivityTestRule<MainActivity>(MainActivity::class.java, true, true)

    private val liveData = MutableLiveData<Resource<Object>>()

    @Before
    open fun setUp() {
        activityRule.activity.viewModelFactory = createViewModelFor(viewModel)
        `when`(viewModel.liveData).thenReturn(liveData)
        viewModel.liveData?.observeForever(mock(Observer::class.java) as Observer<Resource<Object>>)
        liveData.postValue(Resource.success(Object()))
    }

    fun <T : ViewModel> createViewModelFor(model: T): ViewModelProvider.Factory =
        object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                if (modelClass.isAssignableFrom(model.javaClass)) {
                    return model as T
                }
                throw IllegalArgumentException("unexpected model class " + modelClass)
            }
        }
}

有人可以帮我解决这个问题吗?

Can someone help me about this issue please?

推荐答案

JUnit @Rule@Before方法之前进行设置,因此您的活动将在调用setUp()方法之前启动并开始其生命周期.为避免这种情况,请将false作为第三个参数传递给规则构造函数.这表明它不会自动启动活动,因此您可以提前进行设置.

JUnit @Rules do their setup before @Before methods, so your activity is launching and starting its lifecycle before your setUp() method gets called. To avoid this, pass false as the third parameter to the rule constructor. This tells it not to launch the activity automatically, so you can do your setup in advance.

然后,您需要在运行测试之前手动启动活动.您可以创建类似val intent = Intent(InstrumentationRegistry.targetContext, MainActivity::class.java)的意图,然后将其传递给activityRule.launchActivity(intent).

Then, you need to launch the activity manually before you run your tests. You can create an intent like val intent = Intent(InstrumentationRegistry.targetContext, MainActivity::class.java) and then pass it to activityRule.launchActivity(intent).

这篇关于Android体系结构组件ViewModel-如何在测试Activity上模拟ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆