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:
val x = f(Mockito.mock(X::class.java) as X<Int>)
But that would generate an "unchecked cast" warning.
@Mock lateinit var x: X<Int>
But I do not want to use the @Mock
annotation because I like to have my fields final.
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.)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With