Java 在单元测试中使用 assertArrayEquals
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3457941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using assertArrayEquals in unit tests
提问by Eugene
My intention is to use assertArrayEquals(int[], int[])JUnit method described in the APIfor verification of one method in my class.
我的目的是使用API 中assertArrayEquals(int[], int[])描述的 JUnit 方法来验证我的类中的一种方法。
But Eclipse shows me the error message that it can't recognize such a method. Those two imports are in place:
但是 Eclipse 向我显示了它无法识别这种方法的错误消息。这两个进口已经到位:
import java.util.Arrays;
import junit.framework.TestCase;
Did I miss something?
我错过了什么?
采纳答案by Andreas Dolk
This should work with JUnit 4:
这应该适用于 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});
}
}
(answer is based on this wiki article)
(答案基于这篇维基文章)
And this is the same for the old JUnit framework (JUnit 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});
}
}
Note the difference: no Annotations and the test class is a subclass of TestCase (which implements the static assert methods).
注意区别:没有注解,测试类是 TestCase 的子类(它实现了静态断言方法)。
回答by vincintz
Try to add:
尝试添加:
import static org.junit.Assert.*;
assertArrayEqualsis a static method.
assertArrayEquals是一个静态方法。
回答by mdma
If you are writing JUnit 3.x style tests which extend TestCase, then you don't need to use the Assertqualifier - TestCase extends Assert itself and so these methods are available without the qualifier.
如果您正在编写扩展TestCase 的JUnit 3.x 样式测试,那么您不需要使用Assert限定符 - TestCase 扩展 Assert 本身,因此这些方法无需限定符即可使用。
If you use JUnit 4 annotations, avoiding the TestCase base class, then the Assertqualifier 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 styleby some.
如果您使用 JUnit 4 注释,避免使用 TestCase 基类,则Assert需要限定符以及 import org.junit.Assert。在这些情况下,您可以使用静态导入来避免使用限定符,但某些人认为这些样式很差。
回答by carlospiles
This could be useful if you want to use just assertEquals without depending on your Junit version
如果您只想使用 assertEquals 而不依赖于您的 Junit 版本,这可能很有用
assertTrue(Arrays.equals(expected, actual));

