In JUnit 5 parametrized tests. CSV inputs. Is there a way to pass Double.NaN, Double.POSITIVE_INFINITY?

Viewed 698

I am trying to pass Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY and Double.NaN as CSV parameters in JUnit5:

@DisplayName("Testing ActivationFunction.heaviside")
@ParameterizedTest(name = "Testing ActivationFunction.heaviside ({0},{1})")
@CsvSource({
    "Double.NEGATIVE_INFINITY, 0",
    "-100, 0",
    "-1, 0",
    "0, 0.5",
    "1, 1",
    "100, 1",
    "Double.POSITIVE_INFINITY, 0",
    "Double.NaN, Double.NaN"
})
void testActivationFunction_heaviside(double input, double output) {

    assertEquals(output, ActivationFunction.heaviside(input));

}

Unfortunately, it triggers errors like "Error converting parameter at index 0: Failed to convert String "Double.POSITIVE_INFINITY" to type java.lang.Double" in the JUnit5 test runner. Is there a good way to automatically pass such values for testing, or I have just to write a separate test method as follows:

assertEquals(0, Double.NEGATIVE_INFINITY);
assertEquals(1, Double.POSITIVE_INFINITY);
assertEquals(Double.NaN, Double.NaN);
1 Answers

As the error suggests, JUnit is unable to convert the source value to double type. Double.NEGATIVE_INFINITY is a static final member of Double class. You cannot pass a variable name in CsvSource. However, What you have to do is pass String re-presentation of it.

From Java docs:

  • If the argument is NaN, the result is the string "NaN".
  • If m is infinity, it is represented by the string "Infinity"; thus, positive infinity produces the result "Infinity" and negative infinity produces the result "-Infinity".

So you can re-model your code as below:

@DisplayName("Testing ActivationFunction.heaviside")
@ParameterizedTest(name = "Testing ActivationFunction.heaviside ({0},{1})")
@CsvSource({
    "-Infinity, 0",
    "-100, 0",
    "-1, 0",
    "0, 0.5",
    "1, 1",
    "100, 1",
    "Infinity, 0",
    "NaN, NaN"
})
void testActivationFunction_heaviside(double input, double output) {
    System.out.println(input + " :: "+output);
}
Related