Reputation: 113
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.
Upvotes: 11
Views: 7368
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:
Upvotes: 2
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
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