Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit 5 and Arguments.of() with functions

Writing a JUnit 5 parameterized test and need to pass functions to the test using Arguments.of(), but there are 2 compile errors that I don't know how to fix. Any help would be appreciated.

  1. The method of(Object...) in the type Arguments is not applicable for the arguments (boolean, String::length)
  2. The target type of this expression must be a functional interface

public static Stream<Arguments> some() {
    return Stream.of(Arguments.of(true, String::length));
}

@ParameterizedTest
@MethodSource
public <T> void some(final T input, final Function<String, Integer> length) {
}

The following works as expected.

public void sample() {
    some(true, String::length);
}
like image 351
B. Stackhouse Avatar asked Aug 06 '26 03:08

B. Stackhouse


1 Answers

I liked @adrian-redgers solution, but I think overloading a method for each signature needed is a bit overkill.

You only really need to convert the functional interface to an object. So the solution I implemented was:

/**
 * Helps to use {@link org.junit.jupiter.params.provider.Arguments#of(Object...)}, as functional
 * interfaces cannot be converted into an object directly.
 */
public class ArgumentsWrapper {

    private ArgumentsWrapper() {
        throw new IllegalStateException(
                ArgumentsWrapper.class + " util class cannot be instantiated");
    }

    public static <T, U> Function<T, U> wrap(Function<T, U> function) {
        return function;
    }
}

Then, it can be used as:

 public static Stream<Arguments> testMapAlarmTypeConfigWithLanguage() {
    return Stream.of(
        // Statically imported ArgumentsWrapper#wrap
        Arguments.of(null, wrap(AlarmTypeConfig::getNameInEnglish)),
        Arguments.of("en-us", wrap(AlarmTypeConfig::getNameInEnglish)),
        Arguments.of("es-es", wrap(AlarmTypeConfig::getNameInSpanish)));
}
like image 136
Miguel Alorda Avatar answered Aug 07 '26 19:08

Miguel Alorda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!