我不知道为什么,但对于特定路线,它不起作用:
所需路线:
@POST("v2/current-time")
fun utc_time_from_server(): Observable<Response<Void>>
我的测试:
@Test
fun test_call_request_time_success_on_first_header_response() {
// given
var mockedResponse = Any()
var millis = 1L
server.enqueue(MockResponse()
.addHeader("millis", millis)
.setResponseCode(200)
.setBody(""))
// when
doReturn(sharedPrefs).`when`(application).getSharedPreferences(any(), any())
doReturn(Observable.just(mockedResponse)).`when`(api).utc_time_from_server()
presenter.requestTimeSyncPeriodic()
testScheduler.triggerActions()
// then
val calls = Mockito.inOrder(view, database, unbiasedClock)
calls.verify(unbiasedClock).saveServerTime(1L, SystemClock.elapsedRealtime(), application)
}
我的presenter方法称为requestTimeSyncPeriodic(该方法从mainActivity timer每隔一分钟调用一次,只有一个用于测试purpouse)
fun chainTimeRequests(): Observable<Long> {
return apiBag.apiMirror1.utc_time_from_server()
.flatMap { response -> if (response.isSuccessful && response.headers().get("millis") != null) { return@flatMap Observable.just(response) } else { return@flatMap apiBag.apiMirror2.utc_time_from_server() } }
.flatMap { response -> if (response.isSuccessful && response.headers().get("millis") != null) { return@flatMap Observable.just(response) } else { return@flatMap apiBag.apiMainFast.utc_time_from_server() } }
.flatMap { response -> if (response.isSuccessful && response.headers().get("millis") != null) { return@flatMap Observable.just(response.headers().get("millis")!!.toLong()) } else { throw TimeMillisOnHeaderNullException("") } }
}
fun requestTimeSyncPeriodic() {
disposable.add(
chainTimeRequests()
.subscribeOn(scheduler.ui())
.observeOn(scheduler.ui())
.subscribe(
{ utcMillis ->
unbiasedClock.saveServerTime(time = utcMillis, elapsedTime = SystemClock.elapsedRealtime(), application = application) },
{ error ->
error.printStackTrace()
view?.doNothing()
}
)
)
}
我不知道为什么会有这样的结果:
java.lang.ClassCastException: java.lang.Object cannot be cast to retrofit2.Response
但是如果更改测试模拟api调用,则返回到任何其他路由,没有任何相关内容
例如:
doReturn(Observable.just(mockedResponse)).`when`(api).call_any_other_route()
presenter.requestTimeSyncPeriodic()
测试正确通过,我真的无法理解为什么utc\u time\u from\u server不能工作,
abr 18, 2018 4:24:27 PM okhttp3.mockwebserver.MockWebServer$2 execute
INFO: MockWebServer[35751] starting to accept connections
abr 18, 2018 4:24:30 PM okhttp3.mockwebserver.MockWebServer$3 processOneRequest
INFO: MockWebServer[35751] received request: POST /v2/current-time HTTP/1.1 and responded: HTTP/1.1 200 OK