Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit assert double arrays

Tags:

java

junit

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.

like image 531
Kane Turner Avatar asked Jun 04 '16 06:06

Kane Turner


People also ask

How do you assert two arrays are equal?

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.

Can assertEquals compare arrays?

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.

What is the difference between assertEquals and assertSame?

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.

What is the difference between assertThat and assertEquals?

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”.


2 Answers

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

like image 195
Thomas Kläger Avatar answered Oct 18 '22 05:10

Thomas Kläger


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.

like image 29
sprinter Avatar answered Oct 18 '22 05:10

sprinter