AndroidViewModel 和单元测试 [英] AndroidViewModel and Unit Tests

查看:37
本文介绍了AndroidViewModel 和单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AndroidViewModelLiveData 将 Intent 发送到 IntentService 并从 EventBus 接收事件.我需要 Intent 和 EventBus 的应用程序上下文.

I am using AndroidViewModel with LiveData to send Intents to a IntentService and receiving events from an EventBus. I need the Application Context for the Intents and the EventBus.

使用本地测试测试 AndroidViewModel 类的最佳方法是什么?我可以从 Robolectrics RuntimeEnvironment.application 开始,但 AndroidViewModel 似乎没有 shadowOf() 来检查是否将正确的 Intent 发送到正确的接收器.

What is the best way to test AndroidViewModel classes with local tests? I can get it to start with Robolectrics RuntimeEnvironment.application but there doesnt seem to be a shadowOf() for AndroidViewModel to check if the right Intents were sent to the correct receiver.

也许可以通过 Mockito 使用我自己的模拟意图来做到这一点,并将它们注入我的 AndroidViewModel,但这似乎不是很简单.

Perhaps it is somehow possible to do this with Mockito using my own mock-intents and inject them into my AndroidViewModel, but that doesn't seem to be very straightforward.

我的代码如下所示:

class UserViewModel(private val app: Application) : AndroidViewModel(app){
val user = MutableLiveData<String>()

...

private fun startGetUserService() {
    val intent = Intent(app, MyIntentService::class.java)
    intent.putExtra(...)
    app.startService(intent)
}

@Subscribe
fun handleSuccess(event: UserCallback.Success) {
    user.value = event.user
}
}

机器人电动测试:

@RunWith(RobolectricTestRunner.class)
public class Test {
@Test
public void testUser() {
    UserViewModel model = new UserViewModel(RuntimeEnvironment.application)
    // how do I test that startGetUserService() is sending
    // the Intent to MyIntentService and check the extras?
}

推荐答案

我宁愿创建一个你的 Application 类的模拟,因为这样它就可以用来验证它调用了哪些方法以及调用了哪些方法对象被传递给那些方法.所以,它可能是这样的(在 Kotlin 中):

I would rather create a mock of your Application class because then it could be used to verify which methods were called on it and which object were passed to those methods. So, it could be like this (in Kotlin):

@RunWith(RobolectricTestRunner::class)
class Test {
    @Test
    public void testUser() { 
        val applicationMock = Mockito.mock(Application::class.java)
        val model = new UserViewModel(applicationMock)
        model.somePublicMethod();

        // this will capture your intent object 
        val intentCaptor = ArgumentCaptor.forClass(Intent::class.java)
        // verify startService is called and capture the argument
        Mockito.verify(applicationMock, times(1)).startService(intentCaptor.capture())

        // extract the argument value
        val intent = intentCaptor.value
        Assert.assertEquals(<your expected string>, intent.getStringExtra(<your key>))
    }
}

这篇关于AndroidViewModel 和单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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