【发布时间】:2018-04-26 13:55:28
【问题描述】:
我正在尝试使用 Spek 测试 Retrofit api
它在 on{...} 块上抛出 nullPointerException
相关的堆栈跟踪:https://pastebin.com/gy6dLtGg
这是我的测试课
@RunWith(JUnitPlatform::class)
class AccountCheckViewModelTest : Spek({
include(RxSchedulersOverrideRule)
val httpException = mock<HttpException> {
on { code() }.thenReturn(400)
}
given(" account check view model") {
var accountCheckRequest = mock<CheckExistingAccountRequest>()
var accountCheckResponse = mock<CheckExistingAccountResponse>()
var webService = mock<IAPICalls>()
val accountCheckViewModel = spy(VMAccountCheck(webService))
beforeEachTest {
accountCheckRequest = mock<CheckExistingAccountRequest>() {
on { email }.thenReturn("foo@mail")
}
accountCheckResponse = mock<CheckExistingAccountResponse>() {
on { firstName }.thenReturn("foo")
on { email }.thenReturn("foo@mail")
}
webService = mock<IAPICalls> {
on { checkExistingAccount(accountCheckRequest) }.thenReturn(Flowable.just(accountCheckResponse))
}
}
on("api success") {
accountCheckViewModel.checkIfAccountExists(request = accountCheckRequest)
it("should call live data with first name as foo") {
verify(accountCheckViewModel, times(1)).updateLiveData(accountCheckResponse.firstName, accountCheckResponse.email, null)
}
}
}
}
这是我的 RxSchedulersOverrideSpek 类
class RxSchedulersOverrideSpek : Spek({
beforeGroup {
RxJavaPlugins.onIoScheduler(Schedulers.trampoline())
RxJavaPlugins.onComputationScheduler(Schedulers.trampoline())
RxJavaPlugins.onNewThreadScheduler(Schedulers.trampoline())
}
})
【问题讨论】:
-
请注意您在
beforeGroup中遗漏了RxAndroidPlugins.setInitMainThreadSchedulerHandler( __ -> Schedulers.trampoline()); -
是 - NPE 是因为缺少 RxAndroidPlugins.setInitMainThreadSchedulerHandler()
标签: android kotlin retrofit2 rx-java2 spek