JUnit——assertThat(acture,matcher)

使用hamcrest以前須要引入相關的jar包,包括hamcrest-core.1.3.jar和hamcrest-library-1.3.jarjava

具體引入的方法爲:右擊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" ) );
相關文章
相關標籤/搜索