Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using assertArrayEquals in unit tests

My intention is to use assertArrayEquals(int[], int[]) JUnit method described in the API for verification of one method in my class.

But Eclipse shows me the error message that it can't recognize such a method. Those two imports are in place:

import java.util.Arrays; import junit.framework.TestCase; 

Did I miss something?

like image 811
Eugene Avatar asked Aug 11 '10 11:08

Eugene


People also ask

How do you use assertArrayEquals in JUnit?

JUnit 5 TutorialThe assertArrayEquals() method asserts that two object arrays are equal. If they are not, an AssertionError is thrown. If expected and actual are null, they are considered equal. Let's first create Book, BookService classes, and then we will write JUnit test cases to use the assertArrayEquals() method.

What is the purpose of assertArrayEquals message?

7. What is the purpose of assertArrayEquals(“message”, A, B)? Explanation: Asserts the equality of the A and B arrays.

How do you use assertTrue in JUnit?

assertTrue() If you wish to pass the parameter value as True for a specific condition invoked in a method, then you can make use of the. JUnit assertTrue(). You can make use of JUnit assertTrue() in two practical scenarios. By passing condition as a boolean parameter used to assert in JUnit with the assertTrue method.

How do you assert equal arrays?

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.


2 Answers

This would work with JUnit 5:

import static org.junit.jupiter.api.Assertions.*;  assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3}); 

This should work with JUnit 4:

import static org.junit.Assert.*; import org.junit.Test;   public class JUnitTest {       /** Have JUnit run this test() method. */     @Test     public void test() throws Exception {           assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});       } } 

This is the same for the old JUnit framework (JUnit 3):

import junit.framework.TestCase;  public class JUnitTest extends TestCase {   public void test() {     assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});   } } 

Note the difference: no Annotations and the test class is a subclass of TestCase (which implements the static assert methods).

like image 137
Andreas Dolk Avatar answered Oct 11 '22 06:10

Andreas Dolk


This could be useful if you want to use just assertEquals without depending on your Junit version

assertTrue(Arrays.equals(expected, actual)); 
like image 44
carlospiles Avatar answered Oct 11 '22 05:10

carlospiles