JUnit 單元

編寫大型程序的時候,需要些成千上萬的方法和函數,這些函數的功能可能很強大,但是,在程序中,只用到該函數的一小部分功能,並且經過調試可以確定,這一小部分功能是正確的。所以,需要用到單元測試(Unit Testing)。Unit Testing 是指對軟件中的最小可測試單元進行檢查和驗證。單元就是人爲規定的最小的被測試功能模塊。注意:單元測試通常也可以被稱爲模塊測試(Module Testing)。


Module Testing is concerned with the testing of the smallest piect of software for which a separate specification exists.

JUnit is a programmer-oriented testing framework for java.It is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. 


JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit that originated with SUnit.


JUnit is linked as a JAR at compile-time; the framework resides under package junit.framework for JUnit 3.8 and earlier, and under package org.junit for JUnit 4 and later.


A JUnit test fixture is a Java object. With older version of JUnit, fixtures had to inherit form junit.framework.TestCase, but the new tests using JUnit 4 should not do this. Test methods must be annotated by the @Test annotation. If the situation requires it, it is also possible to define a method to execute before(or after) each (or all) of the test methods with the @Before (or @After) and @BeforeClass (or @AfterClass) annotations.


Test Fixture(延伸)

In software testing, a test fixture is a fixed state of the software under test used as a baseline for running tests; also known as the test context. It may also refer to the actions performed in order to bring the system into such a state.

Example of fixtures:

(1). Loading a database with a specific, known set of data

(2). Erasing a hard disk and installing a known clean operating system installation

(3). Copying a specific known set of files

(4).  Preparation of input data and set-up/creation of fake or mock objects.

Software used to systematically run reproducible tests on a piece of software under test is known as a test harness; part of its job is to set up suitable test fixtures.


Test fixture in xUnit

Frequently fixtures are created by handling setUp() and tearDown() events of the unit testing framwork. In setUp() one would create the expected state for the test, and in tearDown() it would clean up what had been set up.

Four phase of a test :

(1). Set up -- Setting up the test fixture.

(2). Exercise -- Interact with the system under test.

(3). Verify -- Determine whether the expected outcome has been obtained.

(4).  Tear down -- Tear down the test fixture to return to the original state.


JUnit 推薦的做法是以test作爲待測試的方法的開頭,這樣這些方法可以被自動找到並被測試。

JUnit 4 是JUnit框架改進,主要目標是利用Java5的Annotation特性簡化測試用例的編寫。

JUnit 測試是程序員測試,即,所謂的白盒測試。


Annotation(延伸)

Annotation 一般是翻譯成元數據。就是描述數據的數據。如上面英文解釋所說的Test Fixture,就是這裏Annotation的相同理解。(有待添補)


發佈了42 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章