測試輔助工具 hamcrest

用了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 > 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 <0>
     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).

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章