Kane Turner
Kane Turner

Reputation: 113

Junit assert double arrays

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

Upvotes: 11

Views: 7368

Answers (3)

David Portilla
David Portilla

Reputation: 56

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:

enter image description here

Upvotes: 2

Thomas Kl&#228;ger
Thomas Kl&#228;ger

Reputation: 21435

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

Upvotes: 16

sprinter
sprinter

Reputation: 27956

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.

Upvotes: 6

Related Questions