gpt4 book ai didi

android - Spek + Retrofit api 测试崩溃

转载 作者:行者123 更新时间:2023-11-30 00:00:25 25 4
gpt4 key购买 nike

我正在尝试使用 Spek 测试 Retrofit api

它在 on{...} block 上抛出 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())
}
})

最佳答案

您应该使用memoized 来正确设置测试值。问题是 accountCheckViewModel 是在 Spek 的发现阶段初始化的,传递给 accountCheckViewModelwebService mock 是那个时候的值(你没有 mock 它的任何方法)。 beforeEachTest 在执行阶段运行,您已将此处的 webService 重新分配给适当的模拟,但 accountCheckViewModel 仍保持先前的值。

given(" account check view model") {
val accountCheckRequest by memoized {
mock<CheckExistingAccountRequest>() {
on { email }.thenReturn("foo@mail")
}
}
val accountCheckResponse by memoized {
mock<CheckExistingAccountResponse>() {
on { firstName }.thenReturn("foo")
on { email }.thenReturn("foo@mail")
}
}
val webService by memoized {
mock<IAPICalls> {
on { checkExistingAccount(accountCheckRequest) }.thenReturn(Flowable.just(accountCheckResponse))
}
}

val accountCheckViewModel by memoized {
spy(VMAccountCheck(webService))
}

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)
}
}
}

关于android - Spek + Retrofit api 测试崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50044879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com