JUnit单元测试笔记
#01 JUnit簡介
1.在項(xiàng)目工程中的Library,add 一個JUnit的Jar包,按需要添加JUnit 3 或 JUnit 4(分為被測試類與測試類較佳)。
2.單元測試是由程序員完成的。
3.Java 5 之前的版本只能 用JUnit 4前的版本(因?yàn)镴Unit 4用到Java 5的新特性----Annotation注解)。
4.JUnit 4只是工具。
#02? setUp(),tearDown()及相關(guān)斷言方法。
1.JUnit3 利用反射,JUnit4利用了注解。
2.JUnit3中setUp()初始方法,而tearDown()銷毀方法;而JUnit4利用@Before和@After來類似的功能。
3.JUnit3中的測試方法必須是以test開頭。
4.單元測試是由程序員編寫的,測試被測試代碼的某一個很小的、特定的功能區(qū)域的代碼。它可以用來確保在代碼或者程序運(yùn)行的環(huán)境中發(fā)生變化后,已經(jīng)存在的功能還是能夠執(zhí)行的。
5.JUnit3中,每一個類都繼承了一個叫做TestCase的類,而TestCase的父類是Assert類;JUnit 4,每一個可以不繼承任何的類,但是仍然可以直接使用import static org.junit.assert.*;在JUnit3中,所有的測試類必須都是TestCase的子類;JUnit4中,測試類可以是一個普通類,也可以去繼承一個類或者實(shí)現(xiàn)一個接口;要實(shí)現(xiàn)測試,只需要在要測試的方法之前加@Test?注釋。
6.相關(guān)斷言方法:
?
assertSame()與assertEquals()并不完全相同;same== 相同,equals==相等
#03 @AfterClass 與@BeforeClass用法
1.@AfterClass,@BeforeClass與@After,@Before,跟Java中的 靜態(tài)塊 和 非靜態(tài)塊 功能相類似。
2.@AfterClass,@BeforeClass用例:數(shù)據(jù)庫的連接(只用于一次)。
#04 @Ignore,@Test(expected = ***.class),@Test(timeout = ^[1-9][0-9]*(millisecond))
#05 JUnit中的Failure,Error與Java 中的Exception,Error 的區(qū)別
?
JUnit中
Failure指的是由于預(yù)期的結(jié)果與實(shí)際運(yùn)行的測試的結(jié)果不同而導(dǎo)致的實(shí)際運(yùn)行單元的結(jié)果不同所導(dǎo)致,例如當(dāng)使用assertEquals()或其它assertXXX()方法斷言失敗時,就會報出Failure,如果發(fā)現(xiàn)Faulure,你就要去檢查你的測試方法或者是被測試方法中編寫的邏輯是否有誤。
Error指的是編寫程序時沒有考慮到的問題。在執(zhí)行測試的斷言之前,程序就因?yàn)槟撤N類型的意外而停止,比喻說我們在操作數(shù)組的時候,因?yàn)榇嫒〕鏊饕龝l(fā)ArrayIndexOutOfBoundsException,這個時候程序就會報出Error,程序?qū)o法運(yùn)行下去,提前結(jié)束,這個時候你要檢查被測試方法中是不是有欠缺考慮到地方。
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.
總結(jié)
以上是生活随笔為你收集整理的JUnit单元测试笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 风色幻想6:主剧情,支线,战斗全攻略(有
- 下一篇: 窗口位置按钮取消_VBA002:“宏”的