??? JUnit 4
已經出來很久了,基本上很多ide都開始支持,當然為了兼容性,一直不太敢用。以前都是懶得寫單元測試,大多數的時候都是
System.out.print。不過現在已經是測試驅動的時代了,為了保持一個良好的習慣,還是需要好好的寫寫單元測試。斷言遠比
System.out.print有用。
??? 看了幾篇文章之后,對JUnit4已經有了基本的概念了。其實很多特性,testNg都已經實現了,挺討厭testNg的xml文件,不過testNg的靈活性還是強大,對于大面積的組件測試比較適合。
??? JUnit 4應該說是使用新的架構寫的,使用了很多java5的新特性。
??? 一個最關鍵的改變,測試類,可以不用繼承那該死的
TestCase了.測試類,可以更加靈活,方法的定義不需要在前面增加test了。
??? 對于測試類來說,只需要做以下簡單的動作:
??? 增加一個@Test,用于標注相應的測試方法。使用Assert類,來進行斷言。
??? import org.junit.Assert; public class AdditionTest { ? private int x =
1; ? private int y =
1; ? @Test public
void addition() { ??? int z = x +
y; ???
Assert.assertEquals(2, z); ? } } |
當然可以使用java 5的static import 功能
import static org.junit.Assert.*; public class AdditionTest { ? private int x =
1; ? private int y =
1; ? @Test public
void addition() { ??? int z = x +
y; ???
assertEquals(2, z); ? } } |
對于setUp 和tearDown來說,以后可以不用再繼承這兩個方法了。可以使用自定義的方法,只需要在前面增加@Before 和@After 注釋即可。
? @Before protected void initialize() { ???
System.setErr(new PrintStream(new ByteArrayOutputStream()));?? ??? inputDir =
new File("data"); ??? inputDir =
new File(inputDir, "xslt"); ??? inputDir =
new File(inputDir, "input"); ??????? } |
? @After protected void disposeDocument() { ? doc = null; ?
System.gc();?? } |
并且可以注釋多個方法。
??? 當然JUnit4
也引入了一個 JUnit 3 中沒有的新特性:類范圍的 setUp() 和 tearDown() 方法。任何用 @BeforeClass 注釋的方法都將在該類中的測試方法運行之前剛好運行一次,而任何用 @AfterClass 注釋的方法都將在該類中的所有測試都運行之后剛好運行一次。
??? 例 如,假設類中的每個測試都使用一個數據庫連接、一個網絡連接、一個非常大的數據結構,或者還有一些對于初始化和事情安排來說比較昂貴的其他資源。不要在每
個測試之前都重新創建它,您可以創建它一次,并還原它一次。該方法將使得有些測試案例運行起來快得多。
? // This class tests a lot of error conditions, which // Xalan annoyingly logs to System.err. This hides
System.err // before each test and restores it after each test. private PrintStream systemErr; @BeforeClass protected void redirectStderr() { ??? systemErr =
System.err; // Hold on to the original value ???
System.setErr(new PrintStream(new ByteArrayOutputStream())); }? @AfterClass protected void tearDown() { ??? // restore
the original value ???
System.setErr(systemErr); } |
??? 異常測試是 JUnit 4 中的最大改進。舊式的異常測試是在拋出異常的代碼中放入
try 塊,然后在 try 塊的末尾加入一個 fail() 語句。
該方法不僅難看,而且試圖挑戰代碼覆蓋工具,因為不管測試是通過還是失敗,總有一些代碼不被執行。在 JUnit 4 中,您現在可以編寫拋出異常的代碼,并使用注釋來聲明該異常是預期的:
? @Test(expected=ArithmeticException.class) ? public void
divideByZero() { ??? int n = 2 /
0; } |
??? 如果該異常沒有拋出(或者拋出了一個不同的異常),那么測試就將失敗。但是如果您想要測試異常的詳細消息或其他屬性,則仍然需要使用舊式的
try-catch 樣式。
??? 測試性能 是單元測試最為痛苦的方面之一。JUnit 4 沒有完全解決這個問題,但是它對這個問題有所幫助。測試可以用一個超時參數來注釋。如果測試運行的時間超過指定的毫秒數,則測試失敗。? @Test(timeout=500) public void
retrieveAllElementsInDocument() { ???
doc.query("http://*"); } |
基本的特性就這么多,這些功能其實都可以在testNg中找到。不過JUnit還是不錯的,對于單元測試來說,這是首選的。
當然為了兼容性,
為了使 JUnit 4 測試可以運行在 JUnit 3 環境中,可以將它們包裝在
JUnit4TestAdapter 中。將下面的方法添加到您的 JUnit
4 測試類中應該就足夠了: ? public static junit.framework.Test suite() { ? return new
JUnit4TestAdapter(AssertionTest.class);???
} |
posted on 2006-10-03 10:36
布衣郎 閱讀(2678)
評論(7) 編輯 收藏 所屬分類:
單元測試