AndroidViewModel和单元测试

时间:2018-06-20 14:29:09

标签: mockito android-testing robolectric

我正在将AndroidViewModelLiveData一起使用,以将Intent发送到IntentService并从EventBus接收事件。我需要意图和EventBus的应用程序上下文。

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

也许可以通过Mockito使用我自己的模拟意图将其注入到我的AndroidViewModel中,但这似乎不是很简单。

我的代码如下:

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测试:

@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?
}

1 个答案:

答案 0 :(得分:2)

我宁愿为您的Application类创建一个模拟,因为这样它可以用于验证在其上调用了哪些方法以及将哪些对象传递给了这些方法。因此,可能就像这样(在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>))
    }
}