0

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?

Westy92
  • 19,087
  • 4
  • 72
  • 54
lannyf
  • 9,865
  • 12
  • 70
  • 152

2 Answers2

1

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)) }
Westy92
  • 19,087
  • 4
  • 72
  • 54
Enes Zor
  • 973
  • 8
  • 14
1

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>()) }
Karsten Gabriel
  • 3,115
  • 6
  • 19
Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70
  • thanks @klitos! the ofType>() passed the compile but the in runtime the map is null so no match is found. How to put in nullable param in the verify? ofType(Map::class), does not work, but the ofType(ICallback::class) actually worked – lannyf Aug 26 '22 at 15:02
  • If you are not looking for specific parameter types, i.e. a null is also acceptable, you can just have `verify { mock.theFunc(any(), any(), any()) }` – Klitos Kyriacou Aug 26 '22 at 15:25
  • I mean, you can use the `or` function to combine matchers, i.e. `verify { mock.theFunc(ofType(), or(ofType(), isNull()), ofType()) }`, but that would be pointless when you can just use `any()`. – Klitos Kyriacou Aug 26 '22 at 15:49