无法找到assertArrayEquals(Object [] o1,Object [] o2)

时间:2009-10-12 05:38:15

标签: java testing junit junit4

我的设置:

  Netbeans 6.7
  Java6
  JUnit 4.5 added as the Test libraries

当我尝试传入两个类数组(强制转换为Object [])时,我收到错误“找不到符号”,我的测试用例将无法编译。

我没有其他断言语句的问题,正如我所说我使用的是JUnit 4.5库。

有没有人知道如何解决这个问题,或观察到这种古怪的行为?

Netbeans能够通过自动完成找到此功能声明,但无法找到它所在的位置,或者可以导航到源。

示例代码:

CustomObject[] coa = { new CustomObject() ....}
CustomObject[] expected = { new CustomObject() ... } 
assertArrayEquals((Object[])coa, (Object[])expected);

4 个答案:

答案 0 :(得分:3)

嗯,Assert.assertArrayEquals是一个静态方法,正如您可以从代码中看到的那样:

 org.junit.Assert.assertArrayEquals(....)

但是在您提供的代码中,您试图将其用作实例方法:

 assertArrayEquals((Object[])coa, (Object[])expected);

只有在您静态导入Assert.*Assert.assertArrayEquals时才会有效。

现在,如果你的其他断言正在运行,我的 guess 就是你仍然从TestCase派生(即编写JUnit测试的“旧”方式)和你的断言正在呼叫TestCase.assertEquals等。

如果您可以给出一个单元测试的简短但完整的示例,其中一个断言有效,但assertArrayEquals没有,我们可能会弄清楚发生了什么。

答案 1 :(得分:1)

您无需完全限定断言或将数组转换为对象数组。只需导入JUnit的正确部分并直接传入数组。你应该从你的例子中反转参数顺序 - 你期望的是第一个(“期望值”),你从测试中得到的是第二个(“实际值”)。这很好用:

import org.junit.*;
import static org.junit.Assert.*;

public class TestJUnitActuallyWorks {

    @Test
    public void myArraysShouldBeIdentical() {

        CustomObject one = new CustomObject();
        CustomObject two = new CustomObject();
        CustomObject three = new CustomObject();

        CustomObject[] expecteds = { one, two, three };
        CustomObject[] actuals = { one, two, three };
        assertArrayEquals(expecteds, actuals);
    }

    private static class CustomObject {}
}

答案 2 :(得分:0)

问题是编译器拒绝调查实际的类..但它会以一个abosulte路径: org.junit.Assert.assertArrayEquals(....

我可能会补充一点烦恼。

答案 3 :(得分:0)

我喜欢SingleShot的答案,除了他的两个数组实际上包含相同的对象。如果对象不是相同的实际对象(不同的对象相同的值但应该相等),那该怎么办。

所以我想我会提高他的答案来说明如何做到这一点。

@Test
public void myArraysShouldBeIdentical() {

    CustomObject one1 = new CustomObject("one");
    CustomObject two1 = new CustomObject("two");
    CustomObject three1 = new CustomObject("three");

    CustomObject one2 = new CustomObject("one");
    CustomObject two2 = new CustomObject("two");
    CustomObject three2 = new CustomObject("three");

    CustomObject[] expecteds = { one1, two1, three1 };
    CustomObject[] actuals = { one2, two2, three2 };
    assertArrayEquals(expecteds, actuals);
}

private static class CustomObject {
    public String value;

    CustomObject(String inValue)
    {
        value = inValue;
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (obj == this)
            return true;
        if (!(obj instanceof CustomObject))
            return false;

        CustomObject rhs = (CustomObject) obj;
        return value == rhs.value;
    }
}
相关问题