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

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

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

 

 
  
  1. Java代码  收藏代码 
  2. @Test   
  3. public void test() throws Exception {   
  4.     int i = 0;   
  5.     assertTrue("The input number should be greater than 0", i > 0);   
  6.   

 

输出的错误信息将是

 
  
  1. java.lang.AssertionError: The input number should be greater than 0 



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

 
 
  
  1. Java代码  收藏代码 
  2.  
  3.     int i = -1;   
  4.     assertConditionSatisfied("i > 0", i > 0, i);   
  5.  
  6.    

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

 
 
  
  1. Java代码  收藏代码 
  2.  
  3.     import static org.junit.Assert.*;   
  4.     import static org.hamcrest.Matchers.*;   
  5.        
  6.         @Test   
  7.         public void test() throws Exception {   
  8.             int i = 0;   
  9.             assertThat(i, greaterThan(0));   
  10.         }   

 

将会有这样的输出

 
  
  1. java.lang.AssertionError: 
  2. Expected: a value greater than <0> 
  3.      got: <0> 

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

更多参考请见:
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).