Hello! I tried to mockk a kotlin `flow` so I can b...
# mockk
m
Hello! I tried to mockk a kotlin
flow
so I can bypass one line of code in my class. Basically I need to bypass the
dropWhile
method so it passes the values in flow to the next method. I tried to create mock like that:
Copy code
@Test
    fun `test mock flow`() = runTest {
        val flow: Flow<Int> = mockk(relaxed = true) {
            coEvery { dropWhile(any()) } returns this
        }
    }
But then i get error
Failed matching mocking signature for left matchers: [any()]
. Is it possible to create a mock that will bypass the
dropWhile
method? Thanks!
j
dropWhile is an extension function, see here for tips: https://mockk.io/#extension-functions
(also, it’s not suspending, so
every {…
instead of
coEvery
should be enough, I think
this works for me:
Copy code
@Test
    fun `test mock flow`(): Unit = runBlocking {
        val flow: Flow<Int> = flowOf(1, 2, 1, 3, 1, 4)
        mockkStatic(Flow<Int>::dropWhile)
        every { flow.dropWhile(any()) } answers { println("mock hit!"); flow }
        flow.dropWhile { it < 3 }.collect { println(it) }
    }
(also, thanks for the puzzle, I clearly needed a distraction 🙂 )
m
Thanks! That helped on the JVM side of things. Unfortunately since I'm using KMM I can not mock
KFunction
using mockkStatic 😕 but that is entirely different problem and Your solution for mocking the
flow
works! 😄
j
outside JVM,
mockkStatic("kotlinx.coroutines.flow.FlowKt")
should work
m
Yes it does 😄 Thank you very much for Your help
590 Views