Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mockk, clearAllMocks or unmockkAll

Tags:

kotlin

mockk

mockk 1.9.3

In the test noticed if did static mock in previous test, the next test will be using same mock. Thought to do a reset at @After, but not sure which one to use clearAllMocks or unmockkAll.

in https://mockk.io/

unmockkAll  unmocks object, static and constructor mocks
clearAllMocks   clears regular, object, static and constructor mocks

but not clear what are the difference by unmocks and clears.

e.g.

@Test
fun test_1() {
    mockkStatic(TextUtils::class)
    every { TextUtils.isEmpty(param } returns true

    //test
    doSomeThingUsingTextUtils()
    // verify
    ... ...
}
@Test
fun test_2() {
    // in this test it does not want the mocked stub behavior

}

What it should use, clear or 'unmock`?

like image 850
lannyf Avatar asked Oct 26 '25 09:10

lannyf


2 Answers

For me, understanding the difference between Clearing and Unmocking was sufficient.

clear - deletes internal state of objects associated with mock resulting in empty object

unmock - re-assigns transformation of classes back to original state prior to mock (Source)

PS: I understand the confusion! I had it as well!

Let me know if you have any questions. Thanks.

like image 93
minchaej Avatar answered Oct 28 '25 03:10

minchaej


clearAllMocks() will undo every { TextUtils.isEmpty(param } returns true.

while unmockkAll() will undo mockkStatic(TextUtils::class)

like image 44
Danzel Avatar answered Oct 28 '25 03:10

Danzel