直接运行类ArithmeticTest.java就可以看到结果.
package com.huaxin.phl; public class Arithmetic { public int add(int a, int b) { return a + b; } public String getString() { return "my name is phl!!!"; } }
package com.huaxin.test; import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import com.huaxin.phl.Arithmetic; public class ArithmeticTest { @BeforeClass public static void beforeClass(){ System.out.println("junit4.8.2 is begin!"); } @AfterClass public static void afterClass(){ System.out.println("junit4.8.2 is end!"); } @Ignore public void testIgnore(){ System.out.println("testIgnore!"); } @Test public void testAdd() { System.out.println("testAdd!!"); assertThat(new Arithmetic().add(4, 3), is(7)); } @Test public void testLength() { System.out.println("testLength!!"); assertThat(new Arithmetic().getString(),containsString("phl")); } }
3)assertThat
使用hamcrest的匹配方法,更自然
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" ) );
4)Failure和Error
1.Failure是指测试失败
2.Error是指测试程序本身出错
5)JUnit4 Annotation
1.@Test: 测试方法
a)(expected=XXException.class)
b)(timeout=xxx)
2.@Ignore: 被忽略的测试方法
3.@Before: 每一个测试方法之前运行
4.@After: 每一个测试方法之后运行
5.@BeforeClass: 所有测试开始之前运行
6.@AfterClass: 所有测试结束之后运行
6)运行多个测试
7)注意1.遵守约定,比如:
a)类放在test包中
b)类名用XXXTest结尾
c)方法用testMethod命名
8)其他框架TestNG
junit下载