`
qiuguo0205
  • 浏览: 240835 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

测试辅助工具 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).

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics