【发布时间】:2020-02-25 12:02:45
【问题描述】:
我想测试服务器没有返回响应的情况,我们触发下一个网络调用(例如搜索查询)。
所以我们基本上在 ViewModel 和 Retrofit 方法中都有一个方法
interface RetrofitApi {
@GET("Some Url")
suspend fun getVeryImportantStuff(): String
}
class TestViewModel(private val api: RetrofitApi) : ViewModel() {
private var askJob: Job? = null
fun load(query: String) {
askJob?.cancel()
askJob = viewModelScope.launch {
val response = api.getVeryImportantStuff()
//DO SOMETHING WITH RESPONSE
}
}
}
并且我想在询问新查询时测试用例,而旧查询没有返回。 对于响应返回测试的情况很容易
@Test
fun testReturnResponse() {
runBlockingTest {
//given
val mockApi:RetrofitApi = mock()
val viewModel = TestViewModel(mockApi)
val response = "response from api"
val query = "fancy query"
whenever(mockApi.getVeryImportantStuff()).thenReturn(response)
//when
viewModel.load(query)
//then
//verify what happens
}
}
但我不知道如何模拟没有返回的挂起函数,以及像这样触发新请求时的测试用例
@Test
fun test2Loads() {
runBlockingTest {
//given
val mockApi:RetrofitApi = mock()
val viewModel = TestViewModel(mockApi)
val response = "response from api"
val secondResponse = "response from api2"
val query = "fancy query"
whenever(mockApi.getVeryImportantStuff())
.thenReturn(/* Here return some fancy stuff that is suspend* or something like onBlocking{} stub but not blocking but dalayed forever/)
.thenReturn(secondResponse)
//when
viewModel.load(query)
viewModel.load(query)
//then
//verify that first response did not happens , and only second one triggered all the stuff
}
}
有什么想法吗?
编辑:我并不真正喜欢 mockito,任何模拟库都会很好:) 问候 沃伊泰克
【问题讨论】:
标签: unit-testing mockito kotlin-coroutines android-viewmodel