简体   繁体   中英

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?

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!"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM