android - 测试失败案例不会与android抛出错误
问题描述
我正在尝试为 kotlin Coroutine 进行单元测试,但是当我尝试对这样的失败案例进行测试时:它失败了
@Test
fun getFailure() {
testCoroutineRule.runBlockingTest {
val error = Error()
whenever(apiService.getApiResponse(key)).thenThrow(error)
verify(observer).onChanged(Resource.error(null,error))
}
}
它给了我一个错误参数不同!通缉:
Argument(s) are different! Wanted:
observer.onChanged(
Resource(status=ERROR, data=null, error=java.lang.Error)
);
Actual invocation has different arguments:
observer.onChanged(
Resource(status=LOADING, data=null, error=null)
);
这是获取在 viewmodel 中声明的 api 数据的函数的方式
fun getResponse(key:String) = liveData(Dispatchers.IO) {
emit(Resource.loading(data = null))
try {
emit(Resource.success(data = apiService.getApiResponse(key)))
}catch (exception:Exception){
emit(Resource.error(data = null,error = exception))
}
}
以及我如何在测试前设置模拟
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
DaggerViewModelComponent.builder()
.apiModule(ApiModuleTest(apiService))
.build()
.inject(mainViewModel)
mainViewModel.getResponse(key).observeForever(observer)
}
解决方案
推荐阅读
- javascript - 从文件加载 XML 并解析?
- c# - 从 Web 服务接收 C# 中的数据
- c# - 使用 EF Core 和内存数据库进行单元测试
- jsf - JSF websocket 更新 viewScope
- java - 如何在我的自定义布局(VBox、HBox 等)元素中获取用 fxml 编写的所有子标签
- react-redux - 根据 first 的响应在 redux observables 中对 ajax 请求进行排序,并单独处理错误和调度动作
- regex - 我想知道满足以下模式的正则表达式:
- c++ - 在 c++ 上创建税收计算程序,未初始化的局部变量出错
- java - Java Hashtable containsValue() 不起作用
- angular - 在地图函数中调用数组