18

I'm using Groovy with JUnit to test my Java code.

I need to test a method foo() which takes in a java.util.function.Function

public void foo(Function<Foo,Bar> func){
    return null; 
}

In my normal code I call foo by passing in a method reference of a method bar ie.

foo(mybar::bar)

How can I test this function in Groovy elegantly?

Using:

mybar.&bar

yields a groovy.lang.Closure<...> which is not compatible with java.util.function.Function.

How else can I achieve this?

ᴘᴀɴᴀʏɪᴏᴛɪs
  • 7,169
  • 9
  • 50
  • 81
  • 3
    Try coercing to `Function`, like this: `foo(mybar.&bar as Function)` – BalRog Dec 23 '16 at 16:42
  • @BalRog That seems to have worked, thanks! – ᴘᴀɴᴀʏɪᴏᴛɪs Dec 23 '16 at 17:04
  • 3
    @balrog you should post your comment as an answer – Bohemian Dec 23 '16 at 21:49
  • 3
    In general I hesitate to post something as an answer unless I have tried it myself and verified that it works. In this case I just didn't have time to do that, so I added it as a comment about something to attempt. Since it *did* work I'll go ahead and post it as an answer after the fact. – BalRog Dec 23 '16 at 22:23

1 Answers1

27

Coerce the final attempt to Function, like this:

foo(mybar.&bar as Function)
BalRog
  • 3,216
  • 23
  • 30