首页 > 解决方案 > 在 JUnit 5 参数化测试中。CSV 输入。有没有办法通过 Double.NaN,Double.POSITIVE_INFINITY?

问题描述

我正在尝试通过Double.NEGATIVE_INFINITY,Double.POSITIVE_INFINITYDouble.NaNJUnit5 中的 CSV 参数:

@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));

}

不幸的是,它会Error converting parameter at index 0: Failed to convert String "Double.POSITIVE_INFINITY" to type java.lang.Double在 JUnit5 测试运行程序中触发类似“”的错误。有没有一种自动传递这些值进行测试的好方法,或者我只需要编写一个单独的测试方法,如下所示:

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

标签: javaunit-testingjunit5

解决方案


正如错误所暗示的,JUnit 无法将源值转换为double类型。Double.NEGATIVE_INFINITY是 Double 类的静态最终成员。您不能在CsvSource. 但是,您需要做的是通过 String 重新表示它。

来自 Java 文档:

  • 如果参数为 NaN,则结果为字符串“NaN”。
  • 如果m为无穷大,则用字符串“Infinity”表示;因此,正无穷大产生结果“Infinity”,负无穷大产生结果“-Infinity”。

因此,您可以重新建模您的代码,如下所示:

@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);
}

推荐阅读