What is Hamcrest?
什么是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 是一个为了测试为目的,且能组合成灵活表达式的匹配器类库。他们也被用于其他用途。
Source
To build, please read BUILDING.txt
源码的构建,请阅读BUILDING.txt
Born in Java, Hamcrest now has implementations in a number of languages.
注意:因为我关注的是Java,所以我选择的是Java Hamcrest,但是Hamcrest还有其它语言的版本。
官网截图:
Java Hamcrest Binaries
上图中我已经将红框内的jar包全部下载下来了,CSDN的下载链接为:http://download.csdn.net/detail/fanxiaobin577328725/9658917
你也可以到上图的链接下载:http://search.maven.org/#search|ga|1|g%3Aorg.hamcrest
explain
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.
Hamcrest由不同的jar包来匹配应用程序的不同的需求。这篇文档描述了这些包的功能和使用。
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.
这是使用第三方框架所必须的核心API。这个Jar包中包含了一组基本的匹配器来执行一般的操作。这个API是稳定的,并且很少会改变。这是你所需要的最基本的库。
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.
这是一个逐渐增加的匹配器库,这些匹配器的实现是基于hamcrest-core.jar的核心功能。这将逐渐变化在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.
这是一个工具,允许实现多个匹配器组合成一个类并通过静态方法返回不同的匹配器,因此使用者没必要记住很多类/包的名称来导入了。这个库是在编译时只在内部使用。在运行的时候没有必要使用其他hamcrest库。
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.
这一个Jar包包含了其它Jar包中的所有类。
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
托管平台网址:https://github.com/hamcrest/JavaHamcrest
Extensions
托管平台网址:https://github.com/hamcrest/JavaHamcrest/wiki/Related-Projects
前言:下文是翻译自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.
本教程向您展示了如何使用hamcres进行t单元测试。
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:
我们先写一个简单的JUnit3测试用例,但是我们不适用JUnit的assertEquals方法,而是使用Hamcrest的构建的assertThat方法和匹配规则,但是这需要静态导入这两部分:
- 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.
assertThat方法是生成测试断言的一个固定方法,在这个例子中,断言的主体是assertThat方法的第一Biscuit对象参数,第二个参数是一个Biscuit对象的匹配器,这个匹配器(matcher)使用equals方法来检查第一个对象是否等于另外一个对象。这个测试用例在Biscuit类定义了equals就可以通过测试。
下面是针对上面的一个自我测试:
源码追踪:(只截取了部分源码)
MatcherAssert:
- 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("
Expected: ")
- .appendDescriptionOf(matcher).appendText("
but: ");
-
- matcher.describeMismatch(actual, description);
-
- throw new AssertionError(description.toString());
- }
- }
- .......
- }
Matchers:
- public class Matchers {
- .......
- public static <T> Matcher<T> equalTo(T operand) {
- return IsEqual.equalTo(operand);
- }
- .......
- }
IsEqual:
- 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);
- }
- ........
- @Factory
- 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的。
饶了一大圈,总的来说就是:比较这两个对象就是调用第一个参数的equals()方法,所以第一个参数的equals()方法的比较方式决定了这个断言是否通过。
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.
Hamcrest自带了一个有用的匹配器库。下面是主要的几个:
Core
- 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
Logical
- 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
Object
- equalTo - test object equality using Object.equals
- hasToString - test Object.toString
- instanceOf, isCompatibleType - test type
- notNullValue, nullValue - test for null
- sameInstance - test object identity
Beans
- hasProperty - test JavaBeans properties
Collections
- 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
Number
- closeTo - test floating point values are close to a given value
- greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo - test ordering
Text
- 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!
Hamcrest绑定了许多有用的匹配器,但是有时候我们需要创建自己的匹配器来满足我们测试的需要。这种情况通常发生在我们使用一段代码片段并且反复测试相同的属性集(在不同的测试中),我们又想把这个代码片段打包成一个断言。通过编写自己的匹配器我们会减少代码的重复性,使测试更加具有可读性!
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:
如果double类型的之有NaN值(不是一个数字),让我们为这种情况写一个我们自己的匹配器,。下面使我们想写的测试:
- 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{
- @Override
- public boolean matchesSafely(Double number){
- return number.isNaN();
- }
-
- public void describeTo(Description description){
- description.appendText("not a number");
- }
-
- @Factory
- 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.
即使notANumber()方法在每次被调用的时候都会创建一个新的匹配器,你不应该认为这是唯一使用的模式匹配器。因此我们应该确保我们的匹配器是stateless,因此单独的实例可以再多个匹配器间重复使用。
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.
如果你定义了很多自定义的匹配器,这会导致我们必须分别的单独导入它们,这让人很烦恼。最好是把它们组织到一个类中,这样它们就可以像导入Hamcrest匹配器库一样,静态导入这一个类就可以了。Hamcrest提供了一种方式来完成这种情况,那就是使用一个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:
首先,创建一个XML的配置文件来罗列出我们所有的匹配器类应该寻找的工厂方法(),如下面的例子:(官网上是空的)
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.
第二步运行,在控制台运行org.hamcrest.generator.config.XmlConfigurator。这个工具将根据XML配置文件生成一个Java类,其包含了所有的XML文件中指定的工厂方法。不带参数的运行它,将会显示一个使用信息,这里有一个输出的例子:
- // 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.
请注意我们现在使用Hamcrest库是我们自定义的匹配器类进口匹配器。
7. Where next?
See FurtherResources.
参考资料:
原文地址:https://blog.csdn.net/fanxiaobin577328725/article/details/52862945