断言失败错误,输出相同

时间:2018-05-28 11:10:58

标签: java

我有一个解析.json文件的类,我正在尝试为解析器方法编写测试代码。

这是我的测试代码,预期和结果与跟踪日志相同。

@Test
public void testParse() throws Exception {
    System.out.println("parse");
    String fileName = "data/fake-1.json";
    RedditListingParser instance = new RedditListingParser();
    ArrayList<RedditThing> expResult = new ArrayList();
    RedditThing thing = new RedditThing("85osel", "ONE TWO TWO THREE THREE THREE", "JoseTwitterFan");
    expResult.add(thing);

    ArrayList<RedditThing> result = instance.parse(fileName);
    assertEquals(expResult, result);
}

这是堆栈日志

expected: java.util.ArrayList<[85osel, JoseTwitterFan, ONE TWO TWO THREE THREE THREE]> but was: java.util.ArrayList<[85osel, JoseTwitterFan, ONE TWO TWO THREE THREE THREE]>
junit.framework.AssertionFailedError
    at reddithottopicsanalyser.RedditListingParserTest.testParse(RedditListingParserTest.java:55)

我不确定这里究竟是什么问题,因为我可以实现一个测试来检查它是否为null并且测试没有问题。

三江源。

1 个答案:

答案 0 :(得分:1)

当涉及到两个列表中的对象时,您正在比较对象引用。为了正确比较对象,您需要覆盖equals方法。在RedditThing类中,添加此代码。

 @Override
 public boolean equals(Object obj) {
    if( !(obj instanceof RedditThing){
        return false;
    }

   RedditThing redditThing2 = (RedditThing)obj;
    return compareEquality(this,redditThing2);
 }




static boolean compareEquality(RedditThing one, RedditThing two){
    //Compare attributes of two objects here and return true/false depending 
      // on comparison
}

然后你可以打电话

assertEquals(expResult, result);