Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 369
Johan Avatar asked Jun 28 '26 07:06

Johan


1 Answers

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<*, *>>())
like image 183
Михаил Нафталь Avatar answered Jun 29 '26 21:06

Михаил Нафталь