我有 Kotlin 类和 Groovy/Spock 测试。当我模拟 Kotlin 类并在模拟上设置属性值时,它无法传递到 Kotlin。
这是一个 Kotlin 实体类,以及使用它的类:
open class TestEntity(var prop: String) {
}
class AClassUnderTest {
fun useATestEntity(testEntity: TestEntity) {
System.out.println("Checking it isn't null within Kotlin code: " + (testEntity.prop))
System.out.println("Code which assumes it is not null: " + testEntity.prop.length)
}
}
这是一个模拟 TestEntity 的测试,模拟 getProp() 方法,然后调用 Kotlin 方法来使用它:
class AClassUnderTestTest extends Specification {
def "UseATestEntity"() {
given:
def cut = new AClassUnderTest()
def testEntityMock = GroovyMock(TestEntity)
testEntityMock.getProp() >> "abc"
System.out.println("Checking it isn't null after mocking: " + (testEntityMock.prop))
when:
System.out.println("Checking it isn't null during when clause: " + (testEntityMock.prop))
cut.useATestEntity(testEntityMock)
then:
noExceptionThrown()
}
}
预期的行为是演示 println 全部显示“abc”并且方法成功
观察到的行为是 Kotlin 中的 println 显示属性为 null,并且该方法失败:
Checking it isn't null after mocking: abc
Checking it isn't null during when clause: abc
Checking it isn't null within Kotlin code: null
Expected no exception to be thrown, but got 'java.lang.NullPointerException'
我做错了什么?
如何模拟 Kotlin 类并为其设置值,以便在 Kotlin 代码以及 Groovy 代码中检索模拟值?
已经尝试过:
- 使用 GroovyStub() 代替 GroovyMock() - 没有区别
- 使用 Mock()/Stub() 而不是 GroovyMock() - 那么该属性在所有 println 的甚至 Groovy 中都为 null (!!?)
- 模拟“testEntityMock.prop >>”而不是“testEntityMock.getProp() >>” - 没有区别
最佳答案
已解决:属性本身也必须声明为开放:
open class TestEntity(
open var prop: String // <-- has to be declared open to be mockable!
) {
}
关于java - 用 spock 模拟的值不会转移到 Kotlin 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67515223/