单元测试之Hamcrest

  • Writing and using Hamcrest Matchers
  • Using Hamcrest for testing - Tutorial
  • Java Hamcrest

Hamcrest

Matchers that can be combined to create flexible expressions of intent

使用Hamcrest

@Test
public void test_hamcrest_using() {
    boolean a = true;
    boolean b = true;
    // all statements test the same
    // a==b
    assertThat(a, is(b));
    assertThat(a, is(equalTo(b)));
    assertThat(a, equalTo(b));

    // 满足任意一个条件
    assertThat("test", anyOf(is("testing"), containsString("est")));

    // 类型判断
    assertThat(Long.valueOf(1), instanceOf(Long.class));

    // 容器数据判断
    List list = Arrays.asList(2, 3, 4);
    assertThat(list, hasSize(3));
    assertThat(list, contains(2, 3, 4));
    assertThat(list, containsInAnyOrder(4, 3, 2));
    assertThat(list, everyItem(greaterThan(1)));

    // 自定义matcher
    assertThat("aaabbbaaaa", RegexMatcher.matchesRegex("a*b*a*"));
}

常用的Hamcrest matchers

  • allOf - matches if all matchers match (short circuits)
  • anyOf - matches if any matchers match (short circuits)
  • not - matches if the wrapped matcher doesn’t match and vice
  • equalTo - test object equality using the equals method
  • is - decorator for equalTo to improve readability
  • hasToString - test Object.toString
  • instanceOf, isCompatibleType - test type
  • notNullValue, nullValue - test for null
  • sameInstance - test object identity
  • hasEntry, hasKey, hasValue - test a map contains an entry, key or value
  • hasItem, hasItems - test a collection contains elements
  • hasItemInArray - test an array contains an element
  • closeTo - test floating point values are close to a given value
  • greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo
  • equalToIgnoringCase - test string equality ignoring case
  • equalToIgnoringWhiteSpace - test string equality ignoring differences in runs of whitespace
  • containsString, endsWith, startsWith - test string matching

自定义Hamcrest matcher

public class RegexMatcher extends TypeSafeMatcher {
    private final String regex;

    public RegexMatcher(final String regex) {
        this.regex = regex;
    }

    @Override
    public void describeTo(final Description description) {
        description.appendText("matches regular expression=`" + regex + "`");
    }

    @Override
    public boolean matchesSafely(final String string) {
        return string.matches(regex);
    }

    // matcher method you can call on this matcher class
    public static RegexMatcher matchesRegex(final String regex) {
        return new RegexMatcher(regex);
    }
}

你可能感兴趣的:(单元测试之Hamcrest)