Java: How to Test on Array Equality

Java: How to test on array equality?

Why is the following code printing "Different."?

Because Arrays.equals performs a shallow comparison. Since arrays inherit their equals-method from Object, an identity comparison will be performed for the inner arrays, which will fail, since a and b do not refer to the same arrays.

If you change to Arrays.deepEquals it will print "Equal." as expected.

Comparing arrays in JUnit assertions, concise built-in way?

Use org.junit.Assert's method assertArrayEquals:

import org.junit.Assert;
...

Assert.assertArrayEquals( expectedResult, result );

If this method is not available, you may have accidentally imported the Assert class from junit.framework.

how to test if two arrays are equal in JUnit testing

You are not really checking the arrays but a custom object MySet. Unfortunately you haven't implemented equals()/hashCode()/toString() correctly.

  1. Fix your MySet.equals signature. It must override Object method boolean equals(Object) and not Boolean equals(MySet a). You can apply @Override annotation to ensure this method is correctly overridden. Without this most of JUnit methods will fail.

  2. Add a corresponding int hashCode() method.

  3. Add a String toString() which will be used by assertion messages.

  4. Change assertEquals(set1.add((MySet)set2).equals(sum), sum.equals(sum));
    should be written as: assertEquals(sum, set1.add((MySet)set2));.

  5. You can try improving assertion message with assertArrayEquals() instead of assertEquals(). You can also try a more modern assertion library e.g. AssertJ.

How to test for equality of Lists of String arrays

The Java documentation requires list equals() to behave as you're using it, so your code would work if these were Lists of Lists:

boolean equals(Object o)

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.

However at the "leaves" you have plain Java arrays. These will use the Object definition of equals, which tests for reference identity, not value equality.

One way around this in your tests is to write a little helper factory routine that accepts a variable argument list of Strings and produces List returns to replace the Java arrays you're currently using. Then all ought to work fine. Your example would look like this:

// A little helper to avoid the awkward syntax
// Arrays.asList(new String [] { "one", "two" })
public static List<String> listOf(String ... strings) {
return Arrays.asList(strings);
}

public static void main(String[] args) {
List<List<String>> left = new ArrayList<>();
left.add(listOf("one", "two"));

List<List<String>> right = new ArrayList<>();
right.add(listOf("one", "two"));

System.out.println(left.equals(right) ? "Yeah!" : "This is not what I want.");
}

Junit-check for equality of array of unique class

You might look a little closer. In the page you linked to, I found this:

 public static void assertArrayEquals(java.lang.String message,
java.lang.Object[] expecteds,
java.lang.Object[] actuals)
throws org.junit.internal.ArrayComparisonFailure

How to test array for equality with multiple input data

JUnit 5 has the concept of "dynamic tests", which allows you to generate test cases at runtime.

Have a look at this example (borrowed from a JUnit 5 workshop):

class PrimeNumbersTest {

@TestFactory
Stream<DynamicTest> test_first_1000_prime_numbers() throws Exception {
return primes().mapToObj(prime -> DynamicTest.dynamicTest(
// Test case name.
"Prime: " + prime,
// Test case content.
() -> assertTrue(PrimeNumbers.isPrime(prime))));
}

private LongStream primes() throws Exception {
Path primesTxt = Paths.get(getClass().getResource("/primes.txt").toURI());
return Files.lines(primesTxt).mapToLong(Long::parseLong);
}

}

test_first_1000_prime_numbers() uses @TestFactory to create a test case for each prime number returned by primes(), which loads them from the external resource primes-1000.txt. For example, IntelliJ displays this as follows:

Sample Image

So, you could dynamically create a test case for each of your setups. This keeps the test data out of the test class and only those tests will fail that contain failed assertions.

Have a look at the user guide or this excellent blog post for further information, but bear in mind that JUnit 5 is still under development.

ArrayList equality JUnit testing

I want to use the assertArrayEquals(ArrayList<Token>, ArrayList<Token>) with these arguments (i.e. arrayList of tokens). But Java tells me I need to create such a method.

It's telling you that you need to create the method because there is no such method in the JUnit library. There isn't such a method in the JUnit library because assertArrayEquals is for comparing arrays, and and ArrayList is not an array—it's a List.

Is there a way to test for the equality of two arrayLists of whatever type in Junit?

You can check the equality of two ArrayLists (really, any two List objects) using equals, so you should be able to use JUnit's assertEquals method and it will work just fine.

How to compare arrays without using .equals and with a false boolean

Instead of immediately returning when they are equal, check for inequalities and if there's one, then return false. If the for loop finishes without returning, then you can safely return true.

if (arrayOne.length == arrayTwo.length) {

for (int i = 0; i < arrayOne.length; i ++) {

if (arrayOne [ i ] != arrayTwo [ i ] ) {

return false;
}

}

return true;

}
return false;


Related Topics



Leave a reply



Submit