天天看点

单元测试

什么是单元测试

写了个类,要给别人用,会不会有bug?怎么办?测试一下。

用main方法测试好不好?不好!

不能一起运行!

大多数情况下需要人为的观察输出确定是否正确

为什么要进行单元测试

重用测试,应付将来的实现的变化。

提高士气,明确知道我的东西是没问题的。

junit4 helloworld

new project

建立类

建立testcase

assertthat

使用hamcrest的匹配方法

放弃旧的断言,使用hamcrest断言

a) 更自然

示例

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" ) );

failure和error

failure是指测试失败

error是指测试程序本身出错

@test: 测试方法

junit4 annotation

a) (expected=xxexception.class)

b) (timeout=xxx)

@ignore: 被忽略的测试方法

@before: 每一个测试方法之前运行

@after: 每一个测试方法之后运行

@beforeclass: 所有测试开始之前运行

@afterclass: 所有测试结束之后运行

遵守约定,比如:

运行多个测试

注意

a) 类放在test包中

b) 类名用xxxtest结尾

c) 方法用testmethod命名

其他框架

testng

继续阅读