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

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

问题描述

我正在将AndroidViewModelLiveData一起使用,以将Intent发送到IntentService并从EventBus接收事件.我需要用于意图和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
}
}

Robolectric测试:

Robolectric Test:

@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天全站免登陆