我正在使用 AndroidViewModel
与 LiveData
将 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/