Reputation: 1971
I have spyk
from mockk
library:
my = spyk(My())
later I am mocking one of the method to return something like:
every { my.method("someString") } returns something
I'm creating this spyk
in a @BeforeAll
method and I'm reusing it a few times but, sometimes I need to call real my.method("someString")
instead of mocked version, but this every{}
mocked it everywhere.
How to force my
to call real method in some cases? Is there any possibility to do that?
Upvotes: 12
Views: 26002
Reputation: 2167
to call original method, you can use answer infix with lambda. This lambda receives MockKAnswerScope
as this
and it contains handy callOriginal()
method
every { my.method("something") } answers { callOriginal() }
example:
class ExampleUnitTest {
private val my = spyk(My())
@Test
fun test() {
val something = "Something"
every { my.method("something") } returns something
// now method will return specific value stated above
assertEquals(something, my.method("something"))
every { my.method("something") } answers { callOriginal() }
// now method will call original code
assertEquals("My something is FUN!", my.method("something"))
}
}
class My {
fun method(item: String): String {
return "My $item is FUN!"
}
}
Upvotes: 35