断言等于2个列表

时间:2018-05-29 14:32:08

标签: java testng

尝试断言2个列表,但失败了:

https://github.com/angular/material2/pull/9885

我试图比较两个List个对象。

这是我的考试班。

public class RestServiceTest {

    HttpClient http = new HttpClient();
    private Gson gson = new Gson();

    @Test
    public void getAllEmployeesTest() throws IOException {
        HttpResponse response = http.get("http://localhost:8087/employee");
        List<Employee> expectedList = new ArrayList<>();
        expectedList.add(new Employee(2, "Yashwant", "Chavan", 30, false));
        Type listType = new TypeToken<ArrayList<Employee>>() {}.getType();

        List<Employee> actualList = gson.fromJson(EntityUtils.toString(response.getEntity()), listType);
        System.out.println(actualList);
        System.out.println(expectedList);
        Assert.assertEquals(actualList,expectedList);
    }
}

3 个答案:

答案 0 :(得分:2)

查看代码,在expectedList中添加一个新的Employee,为该对象提供唯一引用。实际列表将有另一个Employee实例,另一个唯一引用会生成这两个不同的对象。

尽管两个对象具有相同的字段,但assertEquals for list将使用Employee中的equals方法来检查对象是否相同。如果您尚未在Employee中自己实施equals方法,它将检查我之前提到的那些唯一引用。

解决方案是覆盖equals中的Employee方法,如下所示:

@Override
public boolean equals(Object obj) {
   if(!obj instanceof Employee) {
      return false;
   }
   Employee e = (Employee) obj;
   // Add more fields to compare if necessary
   return this.getEmployeeId().equals(e.getEmployeeId()) && this.getAge().equals(e.getAge()); 
 }

应该为您提供您希望的结果。 Possible similar issue and probably better explanation.

如@Zabuza所述,您还需要覆盖hashCode以防HashMapEmployee结合使用。可以找到关于`hashCode的进一步说明here

答案 1 :(得分:0)

请参阅Collection文档:you should implement/override equals method。否则,在比较两个集合(例如List s的Employee)时,将对每个项目的对象ID进行比较。 (另外,请记住实现Employee.hashCode()方法。)

答案 2 :(得分:0)

如果要比较列表,我强烈建议转到assertJ:http://joel-costigliola.github.io/assertj/

使用那个断言将是:

Assertions.assertThat(actualList).containsAll(expectedList);
相关问题