Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

junit arrays not equal test

Tags:

java

arrays

junit

I'm trying to write a test case where my scenario is that two byte arrays should be not equal.

Can I do this with junit?

Or do I have to use something external like Hamcrest? I couldn't change the code in this answer to do the job

Please give a sample.

like image 703
Sam Avatar asked Sep 05 '11 08:09

Sam


People also ask

What is the correct syntax to check if two arrays are equal in JUnit?

equals(sum)); should be written as: assertEquals(sum, set1. add((MySet)set2)); . You can try improving assertion message with assertArrayEquals() instead of assertEquals() .


2 Answers

I prefer doing this the Hamcrest way, which is more expressive:

Assert.assertThat(array1, IsNot.not(IsEqual.equalTo(array2))); 

Or the short version with static imports:

assertThat(array1, not(equalTo(array2))); 

(The IsEqual matcher is smart enough to understand arrays, fortunately.)

Note that a limited version of Hamcrest is part of the JUnit 4.x distribution, so you don't need to add an external library.

like image 171
Sean Patrick Floyd Avatar answered Sep 26 '22 22:09

Sean Patrick Floyd


You can use

assertFalse(Arrays.equals(array1, array2)); 

If you wanted to check they were equal, I would use the following instead.

assertEquals(Arrays.toString(array1), Arrays.toString(array2)); 

as this produces a readable output as to what was different rather than just failing.

like image 32
Peter Lawrey Avatar answered Sep 22 '22 22:09

Peter Lawrey