JUnit测试单元的使用

来源:互联网 发布:400米标准跑道数据 编辑:程序博客网 时间:2024/04/26 23:45

 对于一个Java新手来说,测试方法的正确,一般都会在类中写一个main方法,然后调用需要测试的方法。

 这么做对于一个大型的项目自然是不可取的,对于多个方法,也不能很好的测试各个方法。

  现在甚至会有一种模式称为,Test Driven Development,用测试驱动项目的开发。

因此就有了一个很常用的测试单元工具JUnit,当然还有其他的比如TestNG。不过现在最常用的还是JUnit4。

一、命名

一般会把JUnit放在一个独立的test包中,测试类命名为ClassNameTest.java,其中的测试方法为testMethodName()。

二、测试方法assertThat

然后在测试方法中对所需要测试的方法返回值断言assert,现在比较建议使用的是assertThat。

a)assertThat( n, allOf( greaterThan(1), lessThan(15) ) );assertThat( n, anyOf( greaterThan(16), lessThan(8) ) );assertThat( n, anything() );assertThat( str, is( "xxx" ) );assertThat( str, not( "xxx" ) );b)assertThat( str, containsString( "xxx" ) );assertThat( str, endsWith("xxx" ) ); assertThat( str, startsWith( "xxx" ) ); assertThat( n, equalTo( nExpected ) ); assertThat( str, equalToIgnoringCase( "xxx" ) ); assertThat( str, equalToIgnoringWhiteSpace( "xxx" ) );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( "xxx", "xxx" ) );assertThat( iterable, hasItem ( "xxx" ) );assertThat( map, hasKey ( "xxx" ) );assertThat( map, hasValue ( "xxx" ) );

三、before和after

然后对于一些需要随方法一起启动的,可以放在before和after方法中,比如数据库的连接和关闭。

四、运行结果

然后运行JUnit,只要看见绿条就测试通过了。

当然即使不通过也有两种可能Failure和Error

Failure指的是测试失败,比如说判断是否相等判断是不相符。

Error指的是测试类程序有错误

称为Keep the bargreen to keep the code clean

五、注解

还有就是注解

@Test: 测试方法    (expected=XXException.class)    (timeout=xxx)@Ignore: 被忽略的测试方法@Before: 每一个测试方法之前运行@After: 每一个测试方法之后运行@BeforeClass: 所有测试开始之前运行@AfterClass: 所有测试结束之后运行


详细教程参见JUnit三分钟教程:http://lavasoft.blog.51cto.com/62575/65625

原创粉丝点击