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.
assertArrayEquals. Asserts that two object arrays are equal. If they are not, an AssertionError is thrown with the given message. If expecteds and actuals are null , they are considered equal.
assertArrayEquals() method checks that two object arrays are equal or not. If they are not, it throws an AssertionError with the given message. Incase if expected input and actual inputs are null, then they are considered to be equal.
assertEquals() Asserts that two objects are equal. assertSame() Asserts that two objects refer to the same object. the assertEquals should pass and assertSame should fail, as the value of both classes are equal but they have different reference location.
assertEquals() is the method of Assert class in JUnit, assertThat() belongs to Matchers class of Hamcrest. Both methods assert the same thing; however, hamcrest matcher is more human-readable. As you see, it is like an English sentence “Assert that actual is equal to the expected value”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With