Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking generic interfaces with Kotlin and Mockito

I am trying to mock a generic interface in Kotlin using Mockito. But so far I have found no natural solution. Given:

interface X<T> {
    fun x(): T
}

fun f(x: X<Int>) = x.x()

I could mock X with any of the following:

  1. val x = f(Mockito.mock(X::class.java) as X<Int>)

    But that would generate an "unchecked cast" warning.

  2. @Mock lateinit var x: X<Int>

    But I do not want to use the @Mock annotation because I like to have my fields final.

  3. Introduce a helper function, as the mockito-kotlin library does:

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

    Then call it like this:

    val x: X<Int> = mock()

    But I do not want to use helper functions.

Is there an elegant pure Kotlin way to mock a generic interface with Mockito? (I would prefer a version of 1. without the warning.)

like image 792
jhunovis Avatar asked Nov 08 '16 20:11

jhunovis


People also ask

Does Mockito work with Kotlin?

Mockito has been around since the early days of Android development and eventually became the de-facto mocking library for writing unit tests. Mockito and Mockk are written in Java and Kotlin, respectively, and since Kotlin and Java are interoperable, they can exist within the same project.

Can Mockito mock an interface?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.

What are mocks Mockito?

Mockito is a popular open source framework for mocking objects in software test. Using Mockito greatly simplifies the development of tests for classes with external dependencies. A mock object is a dummy implementation for an interface or a class. It allows to define the output of certain method calls.


1 Answers

Just use mockito-kotlin project. This project contains all must have helpers for mockito. And supports mockito 2.1 as well.

Upd. To deal with "uncheked cast" use Reified type parameters.

You say that "But I do not want to use helper functions.", but why? This is inline function, so in compile time function will be inlined at all call sites will.

like image 86
Ruslan Avatar answered Oct 23 '22 06:10

Ruslan