Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a Java method reference using Groovy for testing purposes

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?

like image 846
ᴘᴀɴᴀʏɪᴏᴛɪs Avatar asked Dec 23 '16 16:12

ᴘᴀɴᴀʏɪᴏᴛɪs


People also ask

How do you call a function in Groovy?

In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.

How does Java method reference work?

Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

Which symbol can be used to reference a method in Java?

The :: operator is used in method reference to separate the class or object from the method name(we will learn this with the help of examples).


1 Answers

Coerce the final attempt to Function, like this:

foo(mybar.&bar as Function)
like image 149
BalRog Avatar answered Sep 21 '22 17:09

BalRog