Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot Capture Mutable List Mockk

Kotlin error when compiling such code mentioned in https://mockk.io/#capturing. What’s wrong actually?

class Foo{
   fun fx(parm: MutableList<Double>) {}
}

val foo = Foo()
val parm: MutableList<Double> = mutableListOf()

every { foo.fx(capture(parm)) }

Error written below

Kotlin: Type mismatch: inferred type is Double but MutableList<Double> was expected

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The capture function expects either a Slot – when you want to capture the parameter of a single invocation – or MutableList – when attempting to capture the parameters of multiple invocations. Both of type T, where T is the type of the parameter. This has to be used in conjunction with verify, not with every.

So you have to use either of the two mechanisms to capture the call arguments.

val param = slot<MutableList<Double>>()
verify { foo.fx(capture(param)) }

// or
val params = mutableListOf<MutableList<Double>>()
verify { foo.fx(capture(params)) }

Also, this only works with a mocked object.
So instead of creating an actual object of type Foo, you would need to create a mock of it.

// set up the mock
val foo = mockk<foo>()
every { foo.func(any()) } just runs

// call the mocked function, most likely you want to do this indirectly instead
foo.fx(mutableListOf())

// assert that the function has been called
val slot = slot<MutableList<Double>>()
verify { foo.fx(capture(slot)) }
val param = slot.captuted

// assert what the function actually has been called with - this example uses "Hamkrest"
assertThat(param, hasSize(equalTo(0)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading