mockk, how to verify a function is called with Map type and interface type

1.4k Views Asked by At

The class has a function:

fun theFunc(uri: Uri, theMap: Map<String, String>?, callback: ICallback) {
  ......
}

and would like to verify it is called with proper params type

io.mockk.verify { mock.theFunc(ofType(Uri::class), ofType(Map<String,  String>::class), ofType(ICallbak::class)) }

the ofType(Uri::class) is ok,

the ofType(Map<String, String>::class got error: enter image description here

the ofType(ICallbak::class) got error:

ICallback does not have a companion object, thus must be initialized here.

How to use the ofType() for Map and interface?

2

There are 2 best solutions below

2
Enes Zor On

You need to use mapOf<String,String>::class

io.mockk.verify { mock.theFunc(ofType(Uri::class), ofType(mapOf<String,String>()::class), ofType(ICallbak)) }

For interface, you can create mocck object. And put it into ofType.

val callbackMock: ICallback = mockk()

io.mockk.verify { mock.theFunc(ofType(Uri::class), ofType(mapOf<String,String>()::class), ofType(callbackMock::class)) }
3
Klitos Kyriacou On

The problem is that generic parameters are lost at runtime due to type erasure, and for this reason the syntax doesn't allow generic parameters to be specified in that context. You can write Map::class but not Map<String, String>::class because a Map<String, String> is just a Map at runtime.

So, you can call it like this:

verify { mock.theFunc(ofType(Uri::class), ofType(Map::class), ofType(ICallback::class)) }

that will work. However, there is also a version of function ofType which takes generic parameters, so you can use this:

verify { mock.theFunc(ofType<Uri>(), ofType<Map<String, String>>(), ofType<ICallback>()) }