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?
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.
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.
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).
Coerce the final attempt to Function
, like this:
foo(mybar.&bar as Function)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With