1

I have code in Kotlin and test code in Java. Since Kotlin and Mockito aren't best friends, I haven't migrated test code to Kotlin.

In Kotlin I have methods with block types. For example:

open fun getProductInfo(resultListener: (List<Deal>)->Unit, errorListener: (Throwable)->Unit)
{
    ...
}

Now I want to stub this method in Java tests. What's the java equivalent of the types? In other words, what should I write in place of ???s below:

doAnswer(invocation -> {
    ??? resultListener = (???) invocation.getArguments()[0];
    // call back resultListener
    return null;
}).when(api).getProductInfo(any(), any());
Mousa
  • 2,190
  • 3
  • 21
  • 34

2 Answers2

3

From the Kotlin in Action book:

The Kotlin standard library defines a series of interfaces, corresponding to different numbers of function arguments: Function0<R> (this function takes no arguments), Function1<P1, R> (this function takes one argument), and so on. Each interface defines a single invoke method, and calling it will execute the function.

In this case, these two functions are both Function1 instances, since they are functions that take one parameter:

Mockito.doAnswer(invocation -> {
    Function1<List<Deal>, Unit> resultListener =
            (Function1<List<Deal>, Unit>) invocation.getArguments()[0];
    Function1<Throwable, Unit> errorListener =
            (Function1<Throwable, Unit>) invocation.getArguments()[1];

    resultListener.invoke(new ArrayList<>());

    return null;
}).when(api).getProductInfo(any(), any());

On another note, you could try mockito-kotlin and the inline version of Mockito to write your tests in Kotlin as well.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
1

Why not to try in Android Studio or IntelliJ, to get Java code from Kotlin:

  • Menu -> Tools -> Kotlin -> Show Kotlin Bytecode
  • Click on the -> Decompile Button
  • Copy the Java code

This way you can continue your work with Mockito, unfortunately you will get redundant lines of code (not much) because Kotlin deal with bytecode.

Lil Bro
  • 236
  • 1
  • 7