Hamcrest

时间:2022-07-11 08:28:37

Hamcrest比起JUnit的assert系列方法来,有更好的可读性,它按照参数从左到右的符合自然的顺序来展示,如actual is(notNullValue()),是对测试断言的改进。同时不会被哪个参数是actual,哪个是expect而混淆。除此之外,Hamcrest提供了更丰富的比较方法,不仅包括基本类型,也包括对象判断、集合/数组判断等一系列方法,同时还有allOf/anyOf这样的组合判断,甚至有判断xml中是否存在相应xpath的判断。

所有的Hamcrest支持的assert全部在org.hamcrest.Matchers类下的静态方法。下面是几个使用例子:

public class CoreShowcase {
@Test
public void test(){
assertThat(true,is(true));
assertThat(false,is(false)); assertThat("2",is(equalTo("2")));
assertThat(2,is(equalTo(2)));
assertThat("aBcD",is(equalToIgnoringCase("abcd")));
assertThat("",isEmptyOrNullString()); assertThat(null,is(nullValue()));
assertThat(2,is(notNullValue()));
assertThat(2,greaterThan(1));
assertThat(2.01,closeTo(2,0.01)); assertThat("xyz",is(anything()));
}
}

  

public class ObjectShowcase {
@Test
public void test(){
Person my=new Person("341024","ZhangKe",32); assertThat(my,instanceOf(Person.class));
assertThat(my,not(sameInstance(new Person("341024"))));
assertThat(my,hasToString(equalTo("341024")));
assertThat(my,hasProperty("name"));
} class Person{
private String idCard;
private String name;
private int age; public Person(String idCard) {
this.idCard = idCard;
} public Person(String idCard, String name, int age) {
this.idCard = idCard;
this.name = name;
this.age = age;
} public String getIdCard() {
return idCard;
} public String getName() {
return name;
} public int getAge() {
return age;
} @Override
public String toString() {
return idCard;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (!idCard.equals(person.idCard)) return false; return true;
} @Override
public int hashCode() {
return idCard.hashCode();
}
}
}

  

public class CombineShowcase {
@Test
public void test(){
//in both/either must have the same type
assertThat("result", both(containsString("r")).and(containsString("u")));
assertThat("result",either(startsWith("x")).or(containsString("r"))); assertThat("result",allOf(notNullValue(),containsString("s")));
assertThat("result",anyOf(notNullValue(),isEmptyString()));
}
}