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.
Fix your
MySet.equals
signature. It must overrideObject
methodboolean equals(Object)
and notBoolean equals(MySet a)
. You can apply@Override
annotation to ensure this method is correctly overridden. Without this most ofJUnit
methods will fail.Add a corresponding
int hashCode()
method.Add a
String toString()
which will be used by assertion messages.Change
assertEquals(set1.add((MySet)set2).equals(sum), sum.equals(sum));
should be written as:assertEquals(sum, set1.add((MySet)set2));
.You can try improving assertion message with
assertArrayEquals()
instead ofassertEquals()
. 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 List
s 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 String
s 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:
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
How to Prevent Parameter Binding from Interpreting Commas in Spring 3.0.5
Compiler Error: "Class, Interface, or Enum Expected"
Difference Between Using Throwable and Exception in a Try Catch
What Does Super.Paintcomponent(G) Do
Tomcat in Idea. War Exploded: Server Is Not Connected. Deploy Is Not Available
Java.Net.Socketexception: Software Caused Connection Abort: Recv Failed
Best Language to Parse Extremely Large Excel 2007 Files
Creating New Generic Object with Wildcard
In Java, How to Know Whether a Class Has Already Been Loaded
Is Autoboxing Possible for the Classes I Create
Check If Int Is Between Two Numbers
Could Not Set the Column Width to Zero I.E. Not Made Column Invisible
Generic Support for Iso 8601 Format in Java 6
Calling Getters on an Object VS. Storing It as a Local Variable (Memory Footprint, Performance)
Receiving "Wrong Name" Noclassdeffounderror When Executing a Java Program from the Command-Line
Is It Necessary to Close Each Nested Outputstream and Writer Separately