use*_*364 6 mockito robolectric android-testing
我使用AndroidViewModelwith LiveData将Intent发送到IntentService并从EventBus接收事件。我需要意图和EventBus的应用程序上下文。
用本地测试测试AndroidViewModel类的最佳方法是什么?我可以从Robolectrics RuntimeEnvironment.application开始,但是似乎没有ShadowOf()用于AndroidViewModel来检查是否将正确的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
}
}
Run Code Online (Sandbox Code Playgroud)
肺动脉测试:
@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?
}
Run Code Online (Sandbox Code Playgroud)
    我宁愿为您的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>))
    }
}
Run Code Online (Sandbox Code Playgroud)