Johan
Johan

Reputation: 40510

Java generics from Kotlin when verifying using Mockito?

I'm using Kotlin 1.6.10, Mockito 4.0.0 and Java 8 and I have a Java interface defined like this:

public interface MyInterface {
    <D, T extends MyObject<T, D>> T doThings(T myObject);
}

An implementation of this interface is used in a Kotlin application and we have a unit test in which we want to make sure that the doThings method is never called using Mockito. In Java I would just do like this:

verify(myInterfaceInstance, never()).doThings(any());

But if I do this in Kotlin I get a compile-time error:

verify(myInterfaceInstance, never()).doThings(any())

Not enough information to infer type variable D

I understand why this is the case, but I cannot get it to work. In this particular case I really don't care about the generic types, I just want to make sure the doThings is never called. I've tried a lot of different things, for example:

verify(myInterfaceInstance, never()).doThings<Any, MyObject<*, Any>>(any())

which fails with:

Type argument is not within its bounds.
Expected:
MyObject<MyObject<*, Any>!, TypeVariable(D)!>!
Found:
MyObject<*, Any!>!

and I've also tried:

verify(myInterfaceInstance, never()).doThings<Any, MyObject<*, *>>(any())

and several other permutations which all seem to fail with roughly the same error message.

So my question is, how can I do the equivalent of Java's verify(myInterfaceInstance, never()).doThings(any()); in Kotlin?

Upvotes: 3

Views: 477

Answers (2)

This compiles fine, but issues a couple of warnings, you could suppress them via respectful annotation:

@Suppress("TYPE_MISMATCH_WARNING", "UPPER_BOUND_VIOLATED_WARNING")
verify(myInterfaceInstance, never()).doThings<Any, MyObject<*, *>?>(any<MyObject<*, *>>())

Upvotes: 1

jcompetence
jcompetence

Reputation: 8383

This is not a Mockito answer, but would the Library Mockk help you? MockK is built specifically for Kotlin so it might have better supports for Generics handling.

The verification would look like:

verify(exactly = 0) { yourClass.doThings(any()) };

https://notwoods.github.io/mockk-guidebook/docs/mocking/verify/

https://mockk.io/#verification-atleast-atmost-or-exactly-times

Upvotes: 1

Related Questions