nhxkutex
nhxkutex

Reputation: 5

Assert equals 2 lists

Trying to assert 2 lists but it fails:

enter image description here

I'm trying to compare two List objects.

Here's my test class.

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);
    }
}

Upvotes: 1

Views: 585

Answers (3)

KoenC
KoenC

Reputation: 316

Seeing your code, you add a new Employee in your expectedList giving that object a unique reference. The actual list will have another instance of Employee with another unique reference making these two different objects.

Although the two objects have the same fields, the assertEquals for list will use the equals method within Employee to check if the objects are the same. If you haven't implemented the equals method yourself inside Employee it will check on those unique references I mentioned before.

A solution would be to override the equals method in Employee like this:

@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()); 
 }

which should give you the results you're hoping for. Possible similar issue and probably better explanation.

As mentioned by @Zabuza you also need to override hashCode as well in case you use something like a HashMap in combination with Employee. Further explanation about `hashCode can be found here.

Upvotes: 2

padilo
padilo

Reputation: 1006

In case of comparing lists I highly recommend to move to assertJ: http://joel-costigliola.github.io/assertj/

Using that that assert would be:

Assertions.assertThat(actualList).containsAll(expectedList);

Upvotes: 0

Vi&#231;
Vi&#231;

Reputation: 356

See the Collection documentation: you should implement/override equals method. Otherwise when comparing two collections (e.g. Lists of Employees) each item will be compared on its object id. (Also, remember to implement Employee.hashCode() method too.)

Upvotes: 0

Related Questions