简体   繁体   中英

Junit assert double arrays

How do I assert that two arrays of double s contain the same elements. There are methods to assert that arrays of integers and other primitive types contain the same elements but not for double s.

JUnit 4.12 has (actually it is already part of 4.6, the oldest version available at github)

org.junit.Assert.assertArrayEquals(double[] expecteds, double[] actuals, double delta)
org.junit.Assert.assertArrayEquals(String message, ddouble[] expecteds, double[] actuals, double delta)

See https://github.com/junit-team/junit4/blob/r4.12/src/main/java/org/junit/Assert.java , source line 482 and 498

If you are not using a version of JUnit that supports double array comparison then the simplest solution would be to use Arrays.equals :

assertTrue(Arrays.equals(array1, array2));

However this won't cope with rounding errors in the way the Junit double asserts do.

Normally you compare doubles with a tolerance for the rounding errors. A solution to this problem using Java 8 and JUnit 5:

  public static final double TOLERANCE = 1e-9;

  @ParameterizedTest
  @MethodSource("getValues")
  public void testArrayOfDoublesEquals(double a, double b)
  {
    assertEquals(a, b, TOLERANCE);
  }

  private static Stream<Arguments> getValues() {
    double[] arrayA = new double[] {1.0, 2.097, 3.98000000001};
    double[] arrayB = new double[] {1.0, 2.097, 3.98000000000};

    List<Arguments> args = new ArrayList<>();
    for(int i = 0; i < arrayA.length; i++) {      
      args.add(Arguments.of(arrayA[i], arrayB[i]));
    }
    return args.stream();
  }

Better than assertArrayEquals because you can visualize the test result element by element:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM