Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test an .equals() method using JUnit and Hamcrest

I have a class List (EDIT: that I wrote myself), with method List.equals, so I want to run something like

List list1 = new List();
List list2 = new List();
assertTrue(list1.equals(list2));

So using matchers and assertThat, I thought maybe

assertThat(list1.equals(list2), is(true));

But this is getting pretty silly...EDIT: perhaps I can write my own matcher

Is there a better way to check if my equals method is working correctly?

This is with JUnit4.5

like image 446
Henry Avatar asked Jul 11 '13 22:07

Henry


People also ask

What is Hamcrest in JUnit?

Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.

What is Hamcrest in testing?

Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit. You can also define custom matcher implementations.

Is assertThat actual is equalTo expected ))) a valid Hamcrest Assert statement?

assertEquals() is the method of Assert class in JUnit, assertThat() belongs to Matchers class of Hamcrest. Both methods assert the same thing; however, hamcrest matcher is more human-readable. As you see, it is like an English sentence “Assert that actual is equal to the expected value”.


2 Answers

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;    

...

assertThat(list1, equalTo(list2));
like image 181
samlewis Avatar answered Oct 01 '22 00:10

samlewis


assertEquals(list1, list2) is the most straightforward way.

like image 23
Tim Boudreau Avatar answered Oct 01 '22 00:10

Tim Boudreau