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

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

也许可以通过Mockito使用我自己的模拟意图将其注入(inject)到我的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
}
}

肺动脉测试:
@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中):

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

10-05 23:25