1

Imagine, I have this line of code:

import org.mockito.Mockito
val mock = Mockito.mock(Sim2ParametersProvider::class.java)

I want to be able to write it like this:

val mock = Sim2ParametersProvider::class.mock()

How do I do this?

I tried

fun <T : kotlin.Any> kotlin.reflect.KClass<T>.mock() = Mockito.mock(this)

but it gives me compiler errors.

Glory to Russia
  • 17,289
  • 56
  • 182
  • 325
  • 2
    Not answering your question, but I found the following function to be more useful: `inline fun mock() = Mockito.mock(T::class.java)` Usage: `val foo = mock()`. In many cases you don't even have to write out the type parameter because of type inference. – Kirill Rakhman Apr 14 '16 at 09:08
  • 2
    Take a look at this nice project: https://github.com/nhaarman/mockito-kotlin – Ruslan Apr 14 '16 at 10:39

1 Answers1

4

It looks like you're slightly mixing up KClass and java Class. The following compiles for me, to extend java classes:

fun <T> Class<T>.mock() = Mockito.mock(this)
val mock1 = FooClass::class.java.mock()

Also the following compiles for me, extending Kotlin KClass:

fun <T: Any> KClass<T>.mock() = Mockito.mock(this.java)
val mock2 = FooClass::class.mock()

Assuming that FooClass is a class, of course.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441