Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockk - spyk mock method only once

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?

like image 380
Ice Avatar asked Dec 11 '22 01:12

Ice


1 Answers

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!"
    }
}
like image 50
V-master Avatar answered Dec 26 '22 12:12

V-master