2011,更要虎虎的
QQ群 測試開發工程師(95934315)
Blog:http://cuckoo2010.blog.163.com/
JUnit Annotation
上一篇 /
下一篇 2010-02-04 23:15:57
/ 個人分類:thinking in testing
前段時間,junit annotation讓我無言了一回,白疼了他兩年,郁悶
junit 現在已經開發到了4.8.1版本,在這個版本中,共有19個annotation。最常用到的也有十來個。下面是無言之后寫的一個junit 程序。沒做什么功能,細心看,或是自己寫一遍,或許那天,你就會用得上。
package com.junit.annotation;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assume.assumeThat;;
@RunWith(Theories.class)
public class AnnotationTest {
@Rule
public TestName testname = new TestName();
@DataPoint
public static String dPoint = "I love JUnit!";
//測試@BeforeClass批注,在整個測試類中只運行一次,有別于@Before。
//test the @BeforeClass annotation
@BeforeClass
public static void testBeforeClass() {
System.out.println("BeforeClass");
}
//測試@Before批注,在每個測試方法運行前執行該方法。
//test the @Before annotation
@Before
public void testBefore() {
System.out.println("Before");
}
//測試@Test批注。
//test the @Test annotation
@Test
public void testMethod() {
Assert.assertEquals("testMethod",testname.getMethodName());
System.out.println("testMethod");
}
//測試@Theory批注。
//test the @Theory annotation
@Theory
public void testDataPoint(String interests) {
//interests必須是I lvoe JUnit!,否則跳過該測試函數。
//interests must be I lvoe JUnit!, or skip the test function.
assumeThat(interests, is("I love JUnit!"));
Assert.assertEquals("testDataPoint",testname.getMethodName());
System.out.println("testDataPoint"+"\n"+dPoint);
}
//測試@Ignore批注
//test the @Ignore annotation
@Ignore
@Test
public void testIgnore() {
Assert.assertEquals("testIgnore",testname.getMethodName());
System.out.println("testIgnore");
}
//測試@After批注,每個test方法執行完成后運行此方法
//test the @After annotation
@After
public void testAfter() {
System.out.println("After");
}
//測試@AfterClass批注,在整個測試類中只運行一次,有別于@After
//test the @AfterClass annotation
@AfterClass
public static void testAfterClass() {
System.out.println("AfterClass");
}
}
執行完,測試通過,從下圖可以知道@Ignore的作用吧

再看下控制臺中輸出的信息

從上圖可以得知,標的@BeforeClass和@AfterClass的測試方法只執行了一次,而@Before和@After在每個標有@Test方法執行前后都會執行一次。這也是這幾個annotation的區別。
而@Rule這個annotation這里只說了一種用法,還有其它七種用法。
附上項目結構圖

這段時間在看一本測試驅動開發的書,是極限編程創始人Kent Beck寫的,非常不錯。讓測試程序運行起來,之后再消除那些重復設計,最終使代碼整潔可用(clean code that works)。呵呵,還沒看完,沒悟到什么。純屬瞎扯蛋!
OK,洗洗睡了,明天上班。
導入論壇
引用鏈接
收藏
分享給好友
推薦到圈子
管理
舉報
TAG:
Annotation
junit
Junit
JUnit
JUNIT