mockito - AndroidViewModel 和单元测试
问题描述
我正在使用AndroidViewModel
withLiveData
将 Intents 发送到 aIntentService
并从 EventBus 接收事件。我需要 Intent 和 EventBus 的应用程序上下文。
使用本地测试测试 AndroidViewModel 类的最佳方法是什么?我可以从 Robolectrics RuntimeEnvironment.application 开始,但 AndroidViewModel 似乎没有 shadowOf() 来检查是否将正确的 Intent 发送到正确的接收器。
也许有可能通过 Mockito 使用我自己的模拟意图来做到这一点并将它们注入到 myAndroidViewModel
中,但这似乎不是很简单。
我的代码看起来像这样:
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>))
}
}
推荐阅读
- pentaho - Pentaho-IVYDC 和 IVYBC 插件
- css - 如何通过 css 选择器在打印中选择第二个或第三个标题
- websphere-liberty - 使用 Liberty JAAS CustomLoginModule 时 401 Unauthorized and cannot getUserRegistry
- php - 包含在php中时可以使用整个文件路径吗?
- java - 使用java获取所有工作表数据
- security - Ubuntu 随机命令消耗了 100% 的杯子使用率
- javascript - 使用 JavaScript、HTML 构建自定义 Flash 视频播放器
- python - 派斯帕克 | 从数据框中分离字符串/整数值
- python - 如何在 python 中合并时间戳并分配标签
- react-native - 设置初始偏移值不起作用