Home > front end >  mockk, how to verify a function is called with Map type and interface type
mockk, how to verify a function is called with Map type and interface type

Time:08-27

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::lass), ofType(Map<String,  String>::class), ofType(ICallbak::class)) }

the ofType(Uri::lass) 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?

CodePudding user response:

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

io.mockk.verify { mock.theFunc(ofType(Uri::lass), 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::lass), ofType(mapOf<String,String>()::class), ofType(callbackMock::class)) }

CodePudding user response:

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>()) }
  • Related