JUnit——assertThat(acture,matcher)

使用hamcrest之前需要引入相关的jar包,包括hamcrest-core.1.3.jar和hamcrest-library-1.3.jar

具体引入的方法为:右击JUnit工程——build path——add external archives

这时在真正测试的时候,还需要引入静态方法import static org.hamcrest.Matchers.*;

package com.bjsxt.junit4.test;

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

import org.junit.Test;

import com.bjsxt.junit4.T;

public class TTest {

     @Test
     public void testAdd() {
          int z = new T().add(5,3);
          assertThat(z,is(8));
     }

}
运行后会报错:
java.lang.SecurityException: class "org.hamcrest.Matchers"'s signer

原因:
JUnit4和hamcrest包的class loader不是同一个

解决方案如下所示:
(1)删除junit包里面的jar包即eclipse自带的library:JUnit4——右击build path——remove
(2)引入最新版本的library的jar包
 
 
 
1.assertThat
2.使用hamcrest的匹配方法
a)更自然
3.示例
a)assertThat( n, allOf( greaterThan(1), lessThan(15) ) );
assertThat( n, anyOf( greaterThan(16), lessThan(8) ) );
assertThat( n, anything() );
assertThat( str, is( "bjsxt" ) );//字符串是不是”bjsxt”
assertThat( str, not( "bjxxt" ) );

b)assertThat( str, containsString( "bjsxt" ) );
assertThat( str, endsWith("bjsxt" ) );
assertThat( str, startsWith( "bjsxt" ) );
assertThat( n, equalTo( nExpected ) );
assertThat( str, equalToIgnoringCase( "bjsxt" ) );  //字符串忽略大小写是否相等
assertThat( str, equalToIgnoringWhiteSpace( "bjsxt" ) );  //字符串忽略空格是否相等

c)assertThat( d, closeTo( 3.0, 0.3 ) );//数值接近3.0 误差不超过0.3
assertThat( d, greaterThan(3.0) );
assertThat( d, lessThan (10.0) );
assertThat( d, greaterThanOrEqualTo (5.0) );//大于等于
assertThat( d, lessThanOrEqualTo (16.0) );

d)assertThat( map, hasEntry( "bjsxt", "bjsxt" ) );//map里面key-value判断
assertThat( iterable, hasItem ( "bjsxt" ) );
assertThat( map, hasKey ( "bjsxt" ) );
assertThat( map, hasValue ( "bjsxt" ) );
 
 
 
 
 
 
 
 
 
 
 
posted @ 2015-03-20 20:34  程序员姜戈  阅读(788)  评论(0编辑  收藏  举报