我想做一些单元测试并模拟一个假的httpresponse
。
我创建了一个httprequest
但是当我做"whenever(repository.search(any())).thenReturn(response)"
时,我在NullPointerException
上有一个“ "search()"
”
当我在设备/模拟器上运行该应用程序时,它运行良好
@Test
fun searchUser_success() {
val expectedUser = User("Louis", 1, "", "", "", "", "", "", "", "", 0.0)
val result = Result(1, false, listOf(expectedUser))
val response = RTResponse.Success(result)
whenever(runBlocking { repository.search("Louis") }).thenReturn(response)
Assert.assertEquals(expectedUser, viewModel.users.value)
}
class SearchRepository(private val searchInterface: SearchInterface) {
suspend fun search(user: String): RTResponse<Result> {
val response = searchInterface.searchAsync(query = user, page = 1, perPage = 10).await()
return try {
if (response.isSuccessful) RTResponse.Success(response.body()!!) else RTResponse.Error(IOException(""))
} catch (e: java.lang.Exception) {
RTResponse.Error(IOException("Unable to fetch users"))
}
}
}
interface SearchInterface {
//http request
@GET("search/users")
fun searchAsync(@Query("q") query: String,
@Query("page") page: Int,
@Query("per_page") perPage: Int): Deferred<Response<Result>>
//singleton instance of Retrofit
companion object Factory { /* build retrofit instance */ }
}