What is Hamcrest?


  Hamcrest is a library of matchers, which can be combined in to create flexible expressions of intent in tests. They've also been used for other purposes.

  Hamcrest 是一个为了测试为目的,且能组合成灵活表达式的匹配器类库。他们也被用于其他用途。 


To build, please read BUILDING.txt


Born in Java, Hamcrest now has implementations in a number of languages.

注意:因为我关注的是Java,所以我选择的是Java Hamcrest,但是Hamcrest还有其它语言的版本。


Java Hamcrest Binaries




1. Introduction
  Hamcrest consists of different jars matching the different needs of applications. This document describes these distributables and the functionality contained in each of them.

2. Overview of distributables
2.1. hamcrest-core.jar

  This is the core API to be used by third-party framework providers. This includes a foundation set of matcher implementations for common operations. This API is stable and will rarely change. You will need this library as a minimum.

2.2. hamcrest-library.jar
  The ever-growing library of Matcher implementations which are based on the core functionality in hamcrest-core.jar. This will grow between releases.


2.3. hamcrest-generator.jar
  A tool to allow many Matcher implementations to be combined into a single class with static methods returning the different matchers so users don't have to remember many classes/packages to import. Generates code. This library is only used internally at compile time. It is not necessary for the use of any of the other hamcrest libraries at runtime.


2.4. hamcrest-integration.jar
  Provides integration between Hamcrest and other testing tools, including JUnit (3 and 4), TestNG, jMock and EasyMock. Uses hamcrest-core.jar and hamcrest-library.jar.

  在使用hamcrest-core.jar and hamcrest-library.jar这两个包时,该包提供了它们和其他测试工具之间的集成,包括JUnit(3和4),TestNG,jMock和EasyMock。

2.5. hamcrest-all.jar
  One jar containing all classes of all the other jars.

2.6. Maven-Versions
  The description above also applies to the hamcrest Maven artifacts. The dependencies of the jars (hamcrest-integration uses hamcrest-library which uses hamcrest-core)is represented by the Maven dependency mechanism. There is no hamcrest-all library in the Maven repo. Just use hamcrest-integration which references all the other hamcrest libraries.

  上面所描述的Jar包同样适用于Maven组件。这些Jar包的依赖性(hamcrest-integration依赖于hamcrest-library并且还依赖于hamcrest-core)可以使用Maven依赖机制。在Maven repo中没有hamcrest-all这个库。只使用hamcrest-integration引用其他hamcrest库。

Source Repository




前言:下文是翻译自Hamcrest官网Documentation的Getting Started,下文中蓝色字体表示我还未翻译,或者说翻译不了的部分,如果哪位可以帮助翻译一下,那真是万分感谢。

The Hamcrest Tutorial(Hamcrest教程)

1. Introduction(介绍)

  Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. There are a number of situations where matchers are invaluble, such as UI validation, or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used. This tutorial shows you how to use Hamcrest for unit testing.


  When writing tests it is sometimes difficult to get the balance right between overspecifying the test (and making it brittle to changes), and not specifying enough (making the test less valuable since it continues to pass even when the thing being tested is broken). Having a tool that allows you to pick out precisely the aspect under test and describe the values it should have, to a controlled level of precision, helps greatly in writing tests that are "just right".Such tests fail when the behaviour of the aspect under test deviates from the expected behaviour, yet continue to pass when minor, unrelated changes to the behaviour are made.

2. My first Hamcrest test(第一个Hamcrest实例)

  We'll start by writing a very simple JUnit 3 test, but instead of using JUnit'sassertEquals methods,we use Hamcrest'sassertThat construct and the standard set of matchers, both of which westatically import:


import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import junit.framework.TestCase;

public class BiscuitTest extends TestCase {
	public void testEquals() {
		Biscuit theBiscuit = new Biscuit("Ginger");
		Biscuit myBiscuit = new Biscuit("Ginger");
		assertThat(theBiscuit, equalTo(myBiscuit));

  The assertThat method is a stylized sentence for making a testassertion. In this example, the subject of the assertion is the objectbiscuitthat is the first method parameter. The second method parameter is a matcher forBiscuitobjects, here a matcher that checks one object is equal to another using theObject equals method. The test passes since theBiscuitclass defines an equals method.





public class MatcherAssert {
	public static <T> void assertThat(T actual, Matcher<? super T> matcher) {
		assertThat("", actual, matcher);

	public static <T> void assertThat(String reason, T actual,
			Matcher<? super T> matcher) {
		if (!(matcher.matches(actual))) {
			Description description = new StringDescription();
			description.appendText(reason).appendText("\nExpected: ")
					.appendDescriptionOf(matcher).appendText("\n     but: ");

			matcher.describeMismatch(actual, description);

			throw new AssertionError(description.toString());


public class Matchers {
       public static <T> Matcher<T> equalTo(T operand) {
        return IsEqual.equalTo(operand);


public class IsEqual<T> extends BaseMatcher<T> {
	private final Object expectedValue;

	public IsEqual(T equalArg) {
		this.expectedValue = equalArg;
       public boolean matches(Object actualValue) {
        return areEqual(actualValue, this.expectedValue);
       private static boolean areEqual(Object actual, Object expected) {
        if (actual == null) {
            return (expected == null);

        if ((expected != null) && (isArray(actual))) {
            return ((isArray(expected)) && (areArraysEqual(actual, expected)));

        return actual.equals(expected);
    public static <T> Matcher<T> equalTo(T operand) {
        return new IsEqual(operand);

执行过程:myBiscuit先传递给equalTo(),然后又传递给了IsEqual.equalTo(),然后根据myBiscuit构造一个IsEqual(暂称为M),并将M返回给assertThat(),assertThat()方法又调用M.matches(theBiscuit )来进行比较,然而M将theBiscuit传递给了areEqual()方法,M的areEqual()调用的就是theBiscuit的equals()方法来进行比较myBiscuit的。


  If you have more than one assertion in your test you caninclude an identifier for the tested value in the assertion:

assertThat("chocolate chips", theBiscuit.getChocolateChipCount(),equalTo(10));
assertThat("hazelnuts", theBiscuit.getHazelnutCount(), equalTo(3));

3. Other test frameworks(其它测试框架)


  Hamcrest has been designed from the outset to integrate with different unit testing frameworks. For example, Hamcrest can be used with JUnit 3 and 4 and TestNG. (For details have a look at the examples that come with the full Hamcrest distribution.) It is easy enough to migrate to using Hamcrest-style assertions in an existing test suite, since other assertion styles can co-exist with Hamcrest's.

  Hamcrest从一开始就设计成与不同的单元测试框架的进行整合,例如Hamcrest可以与JUnit 3和4 以及TestNG进行整合。(更多细节可以参考come with the full Hamcrest distribution)这就很容易迁移到现有的使用Hamcrest格式的测试框架,只要框架的断言可以与Hamcrest的断言共存。

  Hamcrest can also be used with mock objects frameworks by using adaptors to bridge from the mock objects framework's concept of a matcher to a Hamcrest matcher. For example, JMock 1's constraints are Hamcrest's matchers. Hamcrest provides a JMock 1 adaptor to allow you to use Hamcrest matchers in your JMock 1 tests. JMock 2 doesn't need such an adaptor layer since it is designed to use Hamcrest as its matching library. Hamcrest also provides adaptors for EasyMock 2.Again, see the Hamcrest examples for more details.
  Hamcrest也可以通过适配器来适配mock objects(模拟对象)框架的匹配器,例如,JMock 1的约束是Hamcrest的匹配器,JMock 2就不需要这样一个适配器层,只要其被设计为使用Hamcrest作为其匹配库。Hamcrest也为EasyMock 2提供了适配器。

4. A tour of common matchers(常见的匹配器)

Hamcrest comes with a library of useful matchers. Here are some of the most important ones.



  • anything - always matches, useful if you don't care what the object under test is
  • describedAs - decorator to adding custom failure description
  • is - decorator to improve readability - see "Sugar", below


  • allOf - matches if all matchers match, short circuits (like Java &&)
  • anyOf - matches if any matchers match, short circuits (like Java ||)
  • not - matches if the wrapped matcher doesn't match and vice versa


  • equalTo - test object equality using Object.equals
  • hasToString - test Object.toString
  • instanceOf, isCompatibleType - test type
  • notNullValue, nullValue - test for null
  • sameInstance - test object identity


  • hasProperty - test JavaBeans properties


  • array - test an array's elements against an array of matchers
  • 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 - test ordering


  • equalToIgnoringCase - test string equality ignoring case
  • equalToIgnoringWhiteSpace - test string equality ignoring differences in runs of whitespace
  • containsString, endsWith, startsWith - test string matching

5. Sugar

  Hamcrest strives to make your tests as readable as possible. For example, theis matcher is a wrapper that doesn't add any extra behavior to the underlying matcher. The following assertions are all equivalent:

  Hamcrest致力于增强测试用例的可读性。例如, 匹配器是一个包装,不添加任何额外的底层匹配器。下面的断言的作用是完全相同的:

assertThat(theBiscuit, equalTo(myBiscuit)); 
assertThat(theBiscuit, is(equalTo(myBiscuit))); 
assertThat(theBiscuit, is(myBiscuit));

  The last form is allowed since is(T value) is overloaded to return is(equalTo(value)).


6. Writing custom matchers(编写自定义的匹配器)

  Hamcrest comes bundled with lots of useful matchers, but you'll probably find that you need to create your own from time to time to fit your testing needs. This commonly occurs when you find a fragment of code that tests the same set of properties over and over again (and in different tests), and you want to bundle the fragment into a single assertion. By writing your own matcher you'll eliminate code duplication and make your tests more readable!


  Let's write our own matcher for testing if a double value has the value NaN (not a number). This is the test we want to write:

public void testSquareRootOfMinusOneIsNotANumber() { 
assertThat(Math.sqrt(-1), is(notANumber())); 

And here's the implementation:



package org.hamcrest.examples.tutorial;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

public class IsNotANumber extends TypeSafeMatcher{
    public boolean matchesSafely(Double number){
        return number.isNaN();

    public void describeTo(Description description){
        description.appendText("not a number");

    public static Matcher notANumber(){
        return new IsNotANumber();

  The assertThat method is a generic method which takes aMatcher parameterized by the type of the subject of the assertion. We are asserting things about Double values, so we know that we need a Matcher<Double>. For our Matcher implementation it is most convenient to subclass TypeSafeMatcher,which does the cast to a Double for us. We need only implement thematchesSafely method - which simply checks to see if the Double is NaN - and the describeTo method - which is used to produce a failure message when a test fails. Here's an example of how the failure message looks:
  assertThat方法是一个通用的匹配方法,其需要一个匹配器类型的参数,而这个参数是一个断言的形式。我们匹配的是一个Double类型的值,所以我们需要一个Matcher<Double>的匹配器。我们的匹配器继承TypeSafeMatcher是最为方便的,这样我们就可以测试Double这种情况了。我们只需要复写matchesSafely ()方法(这个方法就是简单检查Double值是否是NaN),describeTo ()方法是用来产生一个测试失败时失败消息的。下面的例子就是演示错误信息的显示地:

assertThat(1.0, is(notANumber()));

fails with the message(失败的信息)

java.lang.AssertionError: Expected: is not a number got : <1.0>

  The third method in our matcher is a convenience factory method. We statically import this method to use the matcher in our test:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.examples.tutorial.IsNotANumber.notANumber;
import junit.framework.TestCase;

public class NumberTest extends TestCase{
    public void testSquareRootOfMinusOneIsNotANumber() {
        assertThat(Math.sqrt(-1), is(notANumber()));

  Even though the notANumber method creates a new matcher each time it is called, you should not assume this is the only usage pattern for your matcher. Therefore you should make sure your matcher is stateless,so a single instance can be reused between matches.

6. Sugar generation

  If you produce more than a few custom matchers it becomes annoying to have to import them all individually. It would be nice to be able to group them together in a single class, so they can be imported using a single static import much like the Hamcrest library matchers. Hamcrest helps out here by providing a way to do this by using a generator.
  First, create an XML configuration file listing all the Matcher classes that should be searched for factory methodsannotated with the org.hamcrest.Factory annotation. For example:


  Second, run the org.hamcrest.generator.config.XmlConfigurator command-line tool that comes with Hamcrest. This tool takes the XML configuration file and generates a single Java class that includes all the factory methods specified by the XML file. Running it with no arguments will display a usage message. Here's the output for the example.

// Generated source. package org.hamcrest.examples.tutorial;
public class Matchers{
    public static org.hamcrest.Matcher is(T param1){
        return org.hamcrest.core.Is.is(param1);
    public static org.hamcrest.Matcher is(java.lang.Class param1)    {
        return org.hamcrest.core.Is.is(param1);
    public static org.hamcrest.Matcher is(org.hamcrest.Matcher param1)    {
        return org.hamcrest.core.Is.is(param1);
    public static org.hamcrest.Matcher notANumber(){
        return org.hamcrest.examples.tutorial.IsNotANumber.notANumber();

Finally, we can update our test to use the new Matchers class.

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.examples.tutorial.Matchers.*;
import junit.framework.TestCase;
public class CustomSugarNumberTest extends TestCase{
    public void testSquareRootOfMinusOneIsNotANumber(){
        assertThat(Math.sqrt(-1), is(notANumber()));

Notice we are now using the Hamcrest library is matcher imported from our own custom Matchersclass.

7. Where next?

See FurtherResources.



已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页