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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值