原文:www.cavdar.net/2008/07/21/junit-4-in-60-seconds/
这个周末我研究了一下junit 4,下面是一个简短介绍:
- @Test
用@Test 注解标注你的测试用例集。测试用例不再需要“test"前缀。并且,你的测试用例集类不再需要继承”TestCase"类。- @Test
- public void addition() {
- assertEquals(12 , simpleMath.add( 7 , 5 ));
- }
- @Test
- public void subtraction() {
- assertEquals(9 , simpleMath.substract( 12 , 3 ));
- }
- @Before and @After
分别使用 @Before 和 @After 注解标注 “setup” 和 “tearDown” 方法。他们分别在每个测试用例执行前和结束后运行。- @Before
- public void runBeforeEveryTest() {
- simpleMath = new SimpleMath();
- }
- @After
- public void runAfterEveryTest() {
- simpleMath = null ;
- }
- @BeforeClass and @AfterClass
分 别使用 @BeforeClass 和 @AfterClass 注解标注测试用例集范围的 “setup” 和 “tearDown” 方法。 把他们看做在测试用例集中只执行一次的 setup 和 tearDown 方法。他们分别在测试用例集中所有测试用例执行前和结束后执行一次。- @BeforeClass
- public static void runBeforeClass() {
- // run for one time before all test cases
- }
- @AfterClass
- public static void runAfterClass() {
- // run for one time after all test cases
- }
- 异常处理
使用带 “expected” 参数的 @Test 注解标注期望抛出指定异常的测试用例。“expected” 参数值为希望测试用例抛出的异常的类名。- @Test (expected = ArithmeticException. class )
- public void divisionWithException() {
- // divide by zero
- simpleMath.divide(1 , 0 );
- }
- @Ignore
使用 @Ignore 注解标注你希望忽略的测试用例。如果你愿意可以加一个字符串参数来解释忽略的原因。
- @Ignore ( "Not Ready to Run" )
- @Test
- public void multiplication() {
- assertEquals(15 , simpleMath.multiply( 3 , 5 ));
- }
- 超时
给 “timeout” 参数设置一个以毫秒为单位的时间段。当测试执行时间超过该时间段时,测试失败。- @Test (timeout = 1000 )
- public void infinity() {
- while ( true )
- ;
- }
- 新增断言
比较数组的新断言方法。如果两个数组长度相同,并且对应位置的元素相等,那么两个数组相等,否则不相等。public static void assertEquals(Object[] expected, Object[] actual);
public static void assertEquals(String message, Object[] expected, Object[] actual);- @Test
- public void listEquality() {
- List<Integer> expected = new ArrayList<Integer>();
- expected.add(5 );
- List<Integer> actual = new ArrayList<Integer>();
- actual.add(5 );
- assertEquals(expected, actual);
- }
- JUnit4Adapter
使用Junit4Adapter在 Junit 3 下运行Junit 4的测试。- public static junit.framework.Test suite() {
- return new JUnit4TestAdapter(SimpleMathTest. class );
- }
快乐编程。