1.JDK5允许添加静态类的静态方法
eg:improve static org.junit.Assert.*;
assertEquals(<期望值>,<实际值>);
eg: int z = new T().add(5,3);
assertEquals(8,z);
名言:Keeps the bar green to keeps the code clean!
2.assert重载方法的String message应用:
在junit4之后,Assert类中有许多方法都添加了message提示
eg:assertTrue("a is too small",a>8);
3.assertThat替代了所有的assert方法,由hamcrast包提供匹配支持
下载:http://code.google.com/p/hamcrast/downloads/list 选择hamcrast-1.2.zip完整版本
添加:(Add External Archives)hamcrast-core-1.2.jar,hamcrast-library-1.2.jar
eg: import static org.hamcrast.Matchers.*;
问题:java.lang.SecurityException: class"org.hamcrast.Matches"'s...
解决:必须使用同一个classloader,所以不要用Eclipse自带的junit包,要自己重新引入junit包,问题解决!
(1)assertThat( n, allOf( greaterThan(1), lessThan(15) ) );
assertThat( n, anyOf( greaterThan(16), lessThan(8) ) );
assertThat( n, anything() );
assertThat( str, is( "bjsxt" ) );
assertThat( str, not( "bjsxt" ) );
(2)assertThat( str, containsString( "bjsxt" ) );
assertThat( str, endsWith("bjsxt" ) );
assertThat( str, startsWith( "bjsxt" ) );
assertThat( n, equalTo( nExpected ) );
assertThat( str, equalToIgnoringCase( "bjsxt" ) );
assertThat( str, equalToIgnoringWhiteSpace( "bjsxt" ) );
(3)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) );
(4)assertThat( map, hasEntry( "bjsxt", "bjsxt" ) );
assertThat( iterable, hasItem ( "bjsxt" ) );
assertThat( map, hasKey ( "bjsxt" ) );
assertThat( map, hasValue ( "bjsxt" ) );
4.Failure和Error的区别:Failure是指测试失败,Error是指测试程序本身出错.所以一定要保证0个Error,才能继续进行测试.
JUnit4 Annotation简介
(1)@Test: 测试方法
a) (expected=XXException.class)
b) (timeout=xxx)
(2)@Ignore: 被忽略的测试方法
(3)@Before: 每一个测试方法之前运行
(4)@After: 每一个测试方法之后运行
(5)@BeforeClass: 所有测试开始之前运行
(6)@AfterClass: 所有测试结束之后运行
5.问题:Method Should be static !
@BeforeClass,@AfterClass必须是static静态的才能用,否则就会报错
原因是Test测试类还没有初始化,如果想用就要用static,主要用于搭建测试环境
6.问题:怎样运行测试包里面的所有测试?
解决:在测试包的属性中选择Run all tests...
新的开发模式TDD(Test Driven Development),先写测试就可以确定需求.
7.注意命名规范,要遵守约定,比如:
a)类放在test包中
b)类名用XXXTest结尾
c)方法用testMethod命名
8.代码量不是技术水平的检验标准,记住:豆芽长的在高它也是根菜!