---
title: "测试辅助工具 hamcrest"
author: "qiuguo0205"
date: "2009-12-24T13:44:01Z"
tags: ["Eclipse", "Google", "WordPress", "junit", "单元测试"]
categories: ["编程语言"]
slug: "hamcrest"
draft: false
lastmod: "2010-02-23T15:57:34Z"
id: 555693
url: "https://qiuguo0205.iteye.com/blog/555693"
---

用了JUnit有一段时间了，竟然从来没有用过assertThat。assertThat是JUnit在引入hamcrest后加入的新语句。这也难怪，JUnit的入门教程中使用的都是assertEquals，一看就懂；相对来讲assertThat的语法就比较晦涩难懂了，而且还需要学习一堆不知道什么时候才要用到的匹配器对象。

本来书写简单的单元测试确实并不需要用到assertThat，但是当需要对断言或条件进行测试，并显示条件的详细信息时，使用hamcrest来进行处理就比较好了。

比如希望测试一个整数是否大于0时，使用JUnit原有的语可以这样写

```
    @Test
    public void test() throws Exception {
        int i = 0;
        assertTrue("The input number should be greater than 0", i > 0);
    }
```

 

输出的错误信息将是  
java.lang.AssertionError: The input number should be greater than 0

如果我们需要输出更详细的信息，如 expected condition "i &gt; 0", but actual value was "-1" ，就需要定义自己的Exception，并输入更多的参数，像这样:

```
int i = -1;
assertConditionSatisfied("i > 0", i > 0, i);
```

 

而使用 hamcrest 写起来要简单一些：

```
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

    @Test
    public void test() throws Exception {
        int i = 0;
        assertThat(i, greaterThan(0));
    }
```

 

将会有这样的输出  
java.lang.AssertionError:  
Expected: a value greater than &lt;0&gt;  
     got: &lt;0&gt;

通过定位我们能够找到出错的那一句，从而能够比较快的了解出错的原因。

更多参考请见：  
hamcrest 主页 http://code.google.com/p/hamcrest  
hamcrest 工程的中文简要介绍 http://www.oschina.net/p/hamcrest  
hamcrest 使用简介 http://rdc.taobao.com/blog/qa/?p=3541

 

plus: 一个eclipse中出现错误的解决方法  
java .lang .SecurityException: class "org .hamcrest .Matchers "'s signer information does not match signer information of other classes in the same package

该错误的原因是：我在这里引用了hamcrest-all，而JUnit内部也使用了hamcrest，所以在加载类的时候版本顺序出了错误，只要调整一下hamcrest-all包的位置改在JUnit包之前即可

 

参考自：http://emptylist.wordpress.com/tag/junit/

 

Anyway, to solve the problem you have just to load the Lambdaj jar before the JUnit stuff (Properties, Java Build Path, Order and Export).

[![](http://emptylist.files.wordpress.com/2010/02/order_export.png?w=300&h=222 "Order and Export")](http://emptylist.files.wordpress.com/2010/02/order_export.png)