JUnit 4使用小结
程序员文章站
2022-04-29 19:49:35
...
JUnit
JUnit是Java开发中必备的单元测试工具,目前手里使用的JUnit 4.
Hamcrest
hamcrest使用的断言功能,maven依赖定义如下:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-junit</artifactId>
<version>2.0.0.0</version>
<scope>test</scope>
</dependency>
常用的标注
@Before: 在每个Test方法之前执行
@After 在每个Test方法执行之后
@BefroreClass 在每个测试类启动之前
@AfterClass 在每个测试类启动之后。
@Ignore 忽略当前测试类
@Test 将当前方法进行测试
(expected=xxxException.class) 期待的异常
(timeout=xx) 超时时间
AssertThat
assertThat的判断逻辑,在自于hamcrest。其中常用的方法如下:
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" ) );
assertThat( str, containsString( "bjsxt" ) );
assertThat( str, endsWith("bjsxt" ) );
assertThat( str, startsWith( "bjsxt" ) );
assertThat( n, equalTo( nExpected ) );
assertThat( str, equalToIgnoringCase( "bjsxt" ) );
assertThat( str, equalToIgnoringWhiteSpace( "bjsxt" ) );
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) );
assertThat( map, hasEntry( "bjsxt", "bjsxt" ) );
assertThat( iterable, hasItem ( "bjsxt" ) );
assertThat( map, hasKey ( "bjsxt" ) );
assertThat( map, hasValue ( "bjsxt" ) );
JUnit中的assert
在JUnit中也提供了类似的断言:
assertTrue
assertEquals
代码示例
被测试类:
public class Price {
public int add(int num1, int num2) {
return num1 + num2;
}
}
单元测试方法:
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PriceTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testAdd() {
int result = new Price().add(12, 21);
assertEquals(33, result);
assertTrue(result == 33);
}
@Test
public void testAddThat() {
int result = new Price().add(12, 21);
assertThat(result, is(33));
assertThat("Invalid Result", result, equalTo(33));
}
}