在单元测试中使用 assertArrayEquals

2022-09-01 02:55:39

我的目的是使用API中描述的JUnit方法来验证我的类中的一个方法。assertArrayEquals(int[], int[])

但是Eclipse向我展示了一条错误消息,即它无法识别这样的方法。这两个导入已经到位:

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

我错过了什么吗?


答案 1

这将适用于 JUnit 5

import static org.junit.jupiter.api.Assertions.*;

assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});

这应该适用于 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});
 
    }
}

对于旧的 JUnit 框架 (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});
  }
}

请注意区别:没有注释,测试类是 TestCase 的子类(实现静态断言方法)。


答案 2

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

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

推荐