Mockito mocking parameterized class in Kotlin

If you try to mock parameterized class in Kotlin with Mockito

val mockMyClass = mock<MyClass<String>>(MyClass<String>::class.java)  

You will get this compiler error:

only classes are allowed on the left hand side of a class literal  

That is because Kotlin's class literal syntax is runtime reference. Since generic type arguments are not reified at runtime, we can only obtain an object representing a class, not a type.

Kotlin inline function as a workaround

You can declare a helper function which substituting parameterized class with the desired type at the call site:

inline fun <reified T: Any> mock() = Mockito.mock(T::class.java)  

And use it instead of Mockito's:

val mockMyClass: MyClass<String> = mock()  
comments powered by Disqus