How to understand AssertThat (JUnit)?

3k views Asked by At

To understand JUnit, I have written the following code. In particular, I am interested in the assertThat()-method.

package test;

public class Equals {

    private String x ; 

    public Equals(String a){

        this.x = a; 
    }

    public Equals equals(Equals x ){
            return x; 
    }
}

Then I make a test class to test the equals()-method.

package test;


import static org.junit.Assert.*;

import org.hamcrest.Matcher;
import org.junit.Test;

public class EqualsTest {

    @Test
    public void testEquals() {
        Equals t1 = new Equals("test");

        assertThat(t1, t1.equals("test"));
    }


}

Eclipse underlines assertThat with red and recommends: Create method assertThat(Equals, boolean).

enter image description here

The other assert-methods like assertEquals() and so on are quite straightforward, but this one is not so intuitive for me. I do not understand that. Please help.

best regards,

3

There are 3 answers

1
ygu On

You must use some matcher with this method, not a boolean.

For instance, you can use the is matcher for your purpose:

assertThat("this string", is("this string"));

Take a look at this : http://tutorials.jenkov.com/java-unit-testing/matchers.html

0
Sangwon An On

Recent versions of JUnit now include hamcrest.

In fact, org.junit.Assert.assertThat 's method signature is

public static <T> void assertThat(T actual,
                              org.hamcrest.Matcher<T> matcher)

You can use this way,

assertThat(t1, equalTo("test"));
0
Stefan Birkner On

assertThat is part of the Hamcrest assertion library. Please have a look at Hamcrest's web site: http://hamcrest.org/JavaHamcrest/