1.用Meclipse自带的Junit。
再建个测试用的包com.bjsxt.junit4.test,然后右键单击包,new一个Junit Test Case
选择class under test
输入要测试的类名,这里输入“T”,选择add方法
引入自带的Junit4的包
编写测试类
运行测试类
测试成功
如果要利用assert的一些新特性,就需要引入外部的Junit,Junit还依赖于hamcret,所以这里要引入一下包:hamcrest-core-1.3.0RC2.jar、hamcrest-library-1.3.0RC2.jar、hamcrest-library-1.3.0RC2.jar。
重新编写测试类:
然后运行
Junit报错了,原因是hamcrest的jar包和自带的Junit的ClassLoader用的不是一个,所以要引入我们自己的Junit然后删除自带的Junit就可以正常运行了。
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" ) ); 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 ) ); 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" ) ); assertThat( iterable, hasItem ( "bjsxt" ) ); assertThat( map, hasKey ( "bjsxt" ) ); assertThat( map, hasValue ( "bjsxt" ) );
1. @Test: 测试方法
a) (expected=XXException.class)
b) (timeout=xxx)
2. @Ignore: 被忽略的测试方法
3. @Before: 每一个测试方法之前运行
4. @After: 每一个测试方法之后运行
5. @BeforeClass: 所有测试开始之前运行(static静态的)
6. @AfterClass: 所有测试结束之后运行