Hamcrest是一款用以编写matcher对象的框架,以类库的形式发布。一个matcher对象就是一个明确定义的匹配规则。
Hamcrest只适合用于编写Java单元测试,并不适用于UI验证或数据过滤。
使用Hamcrest的步骤如下:
1.静态导入类
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
说明,其中Matchers类提供了大量用以定义匹配规则的方法。
而assertThat()用以验证测试结果,从而可以不必与具体的测试框架绑定。
2.编写测试用例
...
@Test
public void oneTest(){
Biscuit thisBiscuit = new Biscuit("Ginger");
Biscuit thatBiscuit = new Biscuit("Ginger");
assertThat(thisBiscuit, eq(thatBiscuit));
}
注意这里assertThat()的用法。
如果在一个测试用例中有多个assertThat(),还可以为每个assertThat()起一个唯一的名,示例如下:
...
assertThat("name1", thisBiscuit, eq(thatBiscuit));
assertThat("name2", thisBiscuit, eq(that