#01 JUnit簡介
1.在項目工程中的Library,add 一個JUnit的Jar包,按需要添加JUnit 3 或 JUnit 4(分為被測試類與測試類較佳)。
2.單元測試是由程序員完成的。
3.Java 5 之前的版本只能 用JUnit 4前的版本(因為JUnit 4用到Java 5的新特性----Annotation注解)。
4.JUnit 4只是工具。
#02? setUp(),tearDown()及相關斷言方法。
1.JUnit3 利用反射,JUnit4利用了注解。
2.JUnit3中setUp()初始方法,而tearDown()銷毀方法;而JUnit4利用@Before和@After來類似的功能。
3.JUnit3中的測試方法必須是以test開頭。
4.單元測試是由程序員編寫的,測試被測試代碼的某一個很小的、特定的功能區域的代碼。它可以用來確保在代碼或者程序運行的環境中發生變化后,已經存在的功能還是能夠執行的。
5.JUnit3中,每一個類都繼承了一個叫做TestCase的類,而TestCase的父類是Assert類;JUnit 4,每一個可以不繼承任何的類,但是仍然可以直接使用import static org.junit.assert.*;在JUnit3中,所有的測試類必須都是TestCase的子類;JUnit4中,測試類可以是一個普通類,也可以去繼承一個類或者實現一個接口;要實現測試,只需要在要測試的方法之前加@Test?注釋。
6.相關斷言方法:
?
assertSame()與assertEquals()并不完全相同;same== 相同,equals==相等
#03 @AfterClass 與@BeforeClass用法
1.@AfterClass,@BeforeClass與@After,@Before,跟Java中的 靜態塊 和 非靜態塊 功能相類似。
2.@AfterClass,@BeforeClass用例:數據庫的連接(只用于一次)。
#04 @Ignore,@Test(expected = ***.class),@Test(timeout = ^[1-9][0-9]*(millisecond))
#05 JUnit中的Failure,Error與Java 中的Exception,Error 的區別
?
JUnit中
Failure指的是由于預期的結果與實際運行的測試的結果不同而導致的實際運行單元的結果不同所導致,例如當使用assertEquals()或其它assertXXX()方法斷言失敗時,就會報出Failure,如果發現Faulure,你就要去檢查你的測試方法或者是被測試方法中編寫的邏輯是否有誤。
Error指的是編寫程序時沒有考慮到的問題。在執行測試的斷言之前,程序就因為某種類型的意外而停止,比喻說我們在操作數組的時候,因為存取超出索引會引發ArrayIndexOutOfBoundsException,這個時候程序就會報出Error,程序將無法運行下去,提前結束,這個時候你要檢查被測試方法中是不是有欠缺考慮到地方。
Java中
Exception: The class?Exception
?and its subclasses are a form of?Throwable
?that indicates conditions that a reasonable application might want to catch.
The class?Exception
?and any subclasses that are not also subclasses of?RuntimeException
?are?checked exceptions. Checked exceptions need to be declared in a method or constructor's?throws
?clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
Error: An?Error
?is a subclass of?Throwable
?that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The?ThreadDeath
?error, though a "normal" condition, is also a subclass of?Error
?because most applications should not try to catch it.
A method is not required to declare in its?throws
?clause any subclasses of?Error
?that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is,?Error
?and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.