How to call a lambda callback with mockk

You can use answers: val otm: ObjectToMock = mockk() every { otm.methodToCall(any(), any())} answers { secondArg<(String) -> Unit>().invoke(“anything”) } otm.methodToCall(“bla”){ println(“invoked with $it”) //invoked with anything } Within the answers scope you can access firstArg, secondArg etc and get it in the expected type by providing it as a generic argument. Note that I explicitly … Read more

MockK “io.mockk.MockKException: no answer found for:” error

In your case you mocked the classes being tested. You have two options: get rid of mockk for loginPresenter, just use original object and set properties use spyk to create spy. This is something in between original object and mock The exception is throw because mocks are strict by default, it just do not know … Read more

mocking only one call at a time with mockk

At the excellent post Mocking is not rocket science are documented two alternatives: returnsMany specify a number of values that are used one by one i.e. first matched call returns first element, second returns second element: every { mock1.call(5) } returnsMany listOf(1, 2, 3) You can achieve the same using andThen construct: every { mock1.call(5) } returns … Read more

Mock static java methods using Mockk

After mockk 1.8.1: Mockk version 1.8.1 deprecated the solution below. After that version you should do: @Before fun mockAllUriInteractions() { mockkStatic(Uri::class) val uriMock = mockk<Uri>() every { Uri.parse(“test/path”) } returns uriMock } mockkStatic will be cleared everytime it’s called, so you don’t need to unmock it before using it again. However, if that static namespace … Read more

Unit testing coroutines runBlockingTest: This job has not completed yet

As can be seen in this post: This exception usually means that some coroutines from your tests were scheduled outside the test scope (more specifically the test dispatcher). Instead of performing this: private val networkContext: CoroutineContext = TestCoroutineDispatcher() private val sut = Foo( networkContext, someInteractor ) fun `some test`() = runBlockingTest() { // given … … Read more