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 Function
s? How would you recommend to unit test this method?
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 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".
Check the function behavior using the standard R Function.apply(T t)
method:
Function<St,Obj> func = o.getFunction();
assertEquals(func.apply(value), expectedFunctionResult);
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