开发者

Using assertArrayEquals in unit tests

开发者 https://www.devze.com 2023-01-11 06:20 出处:网络
My intention is to use assertArrayEquals(int[], int[]) JUnit method described in the API for verification of one meth开发者_如何学Pythonod in my class.

My intention is to use assertArrayEquals(int[], int[]) JUnit method described in the API for verification of one meth开发者_如何学Pythonod 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).


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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消