JUnit 单元

来源:互联网 发布:什么是网络设计 编辑:程序博客网 时间:2024/05/01 07:55

编写大型程序的时候,需要些成千上万的方法和函数,这些函数的功能可能很强大,但是,在程序中,只用到该函数的一小部分功能,并且经过调试可以确定,这一小部分功能是正确的。所以,需要用到单元测试(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的相同理解。(有待添补)


原创粉丝点击