简体   繁体   中英

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?

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

如果您只想使用 assertEquals 而不依赖于您的 Junit 版本,这可能很有用

assertTrue(Arrays.equals(expected, actual));

Try to add:

import static org.junit.Assert.*;

assertArrayEquals is a static method.

If you are writing JUnit 3.x style tests which extend TestCase , then you don't need to use the Assert qualifier - TestCase extends Assert itself and so these methods are available without the qualifier.

If you use JUnit 4 annotations, avoiding the TestCase base class, then the Assert qualifier is needed, as well as the import org.junit.Assert . You can use a static import to avoid the qualifier in these cases, but these are considered poor style by some.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM