如何理解AssertThat(JUnit)?

snz8szmq  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(104)

为了理解JUnit,我编写了以下代码。特别是,我对assertThat()-方法感兴趣。

package test;

public class Equals {

    private String x ; 

    public Equals(String a){

        this.x = a; 
    }

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

字符串
然后我创建一个测试类来测试equals()方法。

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用红色在assertThat下面加下划线,并建议:创建方法assertThat(Equals,boolean)。
x1c 0d1x的数据
其他的assert-methods比如assertEquals()等等都很简单,但是这个方法对我来说不是很直观。我不明白。请帮助。
最好的问候,

8ulbf1ek

8ulbf1ek1#

你必须在这个方法中使用一些匹配器,而不是布尔值。
例如,您可以使用is匹配器来实现您的目的:

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

字符串
看看这个:http://tutorials.jenkov.com/java-unit-testing/matchers.html

kwvwclae

kwvwclae2#

assertThat是HamcrestAssert库的一部分。请查看Hamcrest的网站:http://hamcrest.org/JavaHamcrest/

r9f1avp5

r9f1avp53#

JUnit的最新版本现在包括了hamcrest。
实际上,org.junit.Assert. assert的方法签名是

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

字符串
你可以用这种方式,

assertThat(t1, equalTo("test"));

相关问题