Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: unit-testing a method that returns a Function object

I'm trying to write a Java 8 unit test for a method that returns a Function; something like:

class MyObject<X> {
     public Function<X,Obj> getFunction() {...}
 }

In my unit test I create a sample Object and call getFunction() and want to compare that to the expected function which does not work with org.junit.Assert.assertEquals:

@Test
public void getFunction_returnsFunction() {
   final MyObject<St> object = new MyObject<>(..);
   final Function<St,Obj> expectedResult = ...;

   // this does not work
   assertEquals(expectedResult, object.getFunction());
}

Is it even possible to compare two Functions? How would you recommend to unit test this method?

like image 636
Andrea Rendl-Pitrey Avatar asked Nov 29 '18 13:11

Andrea Rendl-Pitrey


People also ask

How does JUnit check return value?

You want to test, first you have to prepare data to test, the input value, the expected value => call test function with input value => get the actual value return by function under test => assert the expected value with the actual value. Here is a list of assert function that you can use.

What will happen if the return type of the JUnit method is string?

What happens if a JUnit test method is declared to return "String"? If a JUnit test method is declared to return "String", the compilation will pass ok. But the execution will fail. This is because JUnit requires that all test methods must be declared to return "void".


1 Answers

Check the function behavior using the standard R Function.apply(T t) method:

Function<St,Obj> func = o.getFunction();
assertEquals(func.apply(value), expectedFunctionResult);
like image 87
Karol Dowbecki Avatar answered Oct 12 '22 10:10

Karol Dowbecki