mockito - AndroidViewModel 和单元测试

标签 mockito android-testing robolectric

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

使用本地测试测试 AndroidViewModel 类的最佳方法是什么?我可以从 Robolectrics RuntimeEnvironment.application 开始,但 AndroidViewModel 似乎没有 shadowOf() 来检查是否将正确的 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>))
    }
}

关于mockito - AndroidViewModel 和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50950654/

相关文章:

java - 使用mockito、ioC和 Autowiring 测试服务

java - 使用接口(interface)对工厂进行单元测试很困难

android - 使用 Robolectric 测试 ViewPager(和 CursorLoader)

android - robolectric 的一些方法找不到影子方法怎么办?

android - 创建要在 src/test 和 src/androidTest 之间共享的 Dagger 2 组件

java - Mockito "thenThrow"没有按预期抛出异常

android - 模拟 android.os.Build.MODEL

android - Sugar ORM 不会创建表

android - 如何防止Android猴子关闭WIFI?

android - 如何使用 Robolectric 测试异步代码