Ashwin
Ashwin

Reputation: 81

In Kotlin MockK What Will Happen After unmockkAll?

What exactly does unmockkall method do?

testImplementation "io.mockk:mockk:1.12.8"


@Test
fun test1() {
    val mockEx: Example = mockk()

    every { mockEx.foo() } returns "mocked"

    unmockkAll()

    val res = mockEx.foo()
    println("res = $res")   // Returns "mocked", this works! Then what will not work after unmock?
}

Even after unmockkAll the mock object still functions as expected, I wanted to know what will not work.

The mock object will throw MockKException after clearAllMocks method but not after unmockkAll method.

Upvotes: 3

Views: 1090

Answers (1)

Sam
Sam

Reputation: 9944

unmockkAll is a companion to the 'static' mocking functions that let you mock top level functions and constructors. For example, mockkObject lets you take a top-level singleton object and turn it into a mock. Similar top-level mocks can be created with mockkStatic and mockkConstructor.

When mocking these kinds of objects or functions, the change applies globally. Every piece of code in the application will now see that object, class or function as mocked. So it's important to be able to undo it again after the test to make sure you don't inadvertently affect other tests. The same doesn't generally apply to individual mockk() objects, because they can be created inside the individual test or test suite and don't exist outside of it.

Here's an example from the docs:

@Before
fun beforeTests() {
    mockkObject(ObjBeingMocked)
    every { ObjBeingMocked.add(1,2) } returns 55
}

@Test
fun willUseMockBehaviour() {
    assertEquals(55, ObjBeingMocked.add(1,2))
}

@After
fun afterTests() {
    unmockkAll()
}

Upvotes: 3

Related Questions