I'm testing my code with mokito-kotlin and I run into a situation where a executed lambda has wrong data. I found out that the "scope" as I know it from JavaScript is different then expected. The this
of the lambda is a different one when I use spy()
.
Here is my simplified test:
@Test
fun strangeLambda() {
open class Foo {
var bar: String? = null
val lambda = { bar }
fun magic() = lambda()
}
Foo().apply {
bar = "jo"
assertEquals(magic(), "jo")
}
spy(Foo()).apply {
bar = "no"
assertEquals(bar, "no") // passes as expected
assertEquals(magic(), "no") // fails: magic returns null!
}
}
What is going on here and how can I fix it? I'm spying the object because I want to verify that some methods are called, but that does not matter here.
My solution is now to subclass the class I'm interested in and making the constructor internal so that just I can use it. In the subclass I check if I get the params I expect.