gpt4 book ai didi

kotlin - 模拟私有(private)属性(property)

转载 作者:行者123 更新时间:2023-12-01 23:35:29 26 4
gpt4 key购买 nike

假设我们有一个这样的类:

class Whatever {
private var something = false

fun aMethod(): Int {
return if( something ) {
1
} else {
0
}
}
}

根据documentation ,看起来我应该能够执行以下操作:

val classUnderTest = spyk(Whatever())

every { classUnderTest getProperty "something" } returns true

assertThat(classUnderTest.aMethod()).isEqualTo(1)

但我收到错误:io.mockk.MockKException:每个 { ... } block 内缺少调用

我使用的是mockk 1.8.5,kotlin 1.2.51

最佳答案

尝试使用答案而不是返回,如下所示:

val mock = spyk(MockCls(), recordPrivateCalls = true)

every { mock.property } answers { fieldValue }
every { mock getProperty "property" } propertyType Int::class answers { fieldValue + 6 }
every { mock setProperty "property" value any<Int>() } propertyType Int::class answers { fieldValue += value }
every { mock.property = any() } propertyType Int::class answers {
fieldValue = value + 1
} andThen {
fieldValue = value - 1
}

关于kotlin - 模拟私有(private)属性(property),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51316105/

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