8

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?

Ice
  • 1,783
  • 4
  • 26
  • 52

1 Answers1

32

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!"
    }
}
V-master
  • 1,957
  • 15
  • 18