JUnit User Manual

Source: Internet
Author: User
Title JUnit User ManualSelect blog from legendinfo
Keywords JUnit User Manual
Source
Unit test is an essential part of XP development. As unit test, JUnit is the preferred tool. This article briefly describes the basic usage of JUnit from the usage purpose, how to use it, and the issues that need to be considered during use.

Purpose
JUnit is the framework for writing unit test in Java. Currently, most popular unit test tools are extended on JUnit. Currently, its version is junit3.8.1 and can be downloaded from www.junit.org.

Usage
1. The basic steps are as follows:

-Create the test case required by unit test from JUnit. Framework. testcase.

-The writing test method provides a test method similar to the following function signature:

Public void testxxxxx ();

-Compile the test case class.

-Run. Start JUnit test runner to run the test case.

JUnit provides two basic test Runner: character interface and graphical interface. The startup commands are as follows:

A graphical interface:

Java JUnit. swingui. testrunner XXXXX

B character interface:

Java JUnit. textui. testrunner XXXXX

2. Example:

Import JUnit. frmework. testcase;

Public class testsample extends testcaset {

Public void testmethod1 (){

Asserttrue (true );

}

}

3. Setup and teardown. These two functions provide initialization and anti-initialization for each test method in JUnit framework. Setup is called before each test method is called, and is responsible for initializing the test environment required for the test method. teardown is called after each test method is called, and is responsible for revoking the test environment. The relationship between them and the test method can be described as follows:

Test start-> setup-> testxxxx-> teardown-> test end

4. Example:

Import JUnit. frmework. testcase;

Public class testsample extends testcaset {

Protected void setup (){

// Initialize ......

}

Public void testmethod1 (){

Asserttrue (true );

}

Potected void teardown (){

// Cancel initialization ......

}

}

5. differentiate fail and exception.

-Fail: Expected error. Cause: assert function errors (such as assertfalse (true); fail function generation (such as fail (......)).

-Exception: An Unexpected error. It is an exception thrown when the unit test program runs. It is similar to the runtime exception thrown during normal code execution.

For functions such as assert and fail, see javadoc of JUnit.

6. Example:

Import JUnit. frmework. testcase;

Public class testsample extends testcaset {

Protected void setup (){

// Initialize ......

}

Public void testmethod1 (){

......

Try {

Boolean B = ......

Asserttrue (B );

Throw new exception ("This is a test .");

Fail ("unable point."); // It cannot be reached

} Catch (exception e ){

Fail ("Yes, I catch u"); // It should arrive at the point

}

......

}

Potected void teardown (){

// Cancel initialization ......

}

}

7. Assemble testsuite and run more test. In JUnit, test, testcase, and testsuite constitute composiste pattern. By assembling your own testsuite, you can call all testcase added to this testsuite. In addition, these testsuite definitions can be assembled into larger testsuite, which also facilitates the management and maintenance of the ever-increasing testcase.

Another benefit is that it can be called from any node of the testcase tree (testsuite or testcase) to complete all testcase calls under this node. This improves the flexibility of unit test.

8. Example:

Import JUnit. Framework. test;

Import JUnit. Framework. testsuite;

Public class testall {

Public class testall {

// Define a suite. The function of JUnit can be considered as similar to the main of a Java application.

Public Static Test Suite (){

Testsuite suite = new testsuite ("running all tests .");

Suite. addtestsuite (testcase1.class );

Suite. addtestsuite (testcase2.class );

Return suite;

}

}

Run the same testcase as run. For more information, see Step 1 "run ".

9. Use ant JUnit task. In addition to using Java to directly run JUnit, we can also use the JUnit task and ant provided by JUnit to run it. The main ant tasks involved are as follows:

-<JUnit>: defines a JUnit task.

-<Batchtest>, located in <JUnit>, run multiple testcase

-<Test>, located in <JUnit>, run a single testcase

-<Formatter>, located in <JUnit>, defines a test result output format

-<Junitreport>: defines a junitreport task.

-<Report>, located in <junitreport>, outputs a JUnit report.

For more information about the syntax, see related documents.

10. Example:

<JUnit printsummary = "yes" haltonfailure = "no">

<Classpath>

<Path refID = "classpath"/>

<Pathelement location = "$ {Dist. JUnit}"/>

</Classpath>

<Formatter type = "Brief" usefile = "false"/>

<Formatter type = "XML"/>

<Batchtest todir = "$ {Doc. junitreport}">

<Fileset dir = "$ {Dist. JUnit}" includes = "**/* test. Class"/>

</Batchtest>

</JUnit>

<Junitreport todir = "$ {Doc. junitreport}">

<Fileset dir = "$ {Doc. junitreport}">

<Include name = "test *-*. xml"/>

</Fileset>

<Report format = "frames" styledir = "$ {JUnit. styledir}" todir = "$ {Doc. junitreport}"/>

</Junitreport>

Checklist
The use of JUnit is not very difficult, but it is not easy to write a good testcase. A bad testcase often wastes time and does not play a practical role. On the contrary, a good testcase can not only point out the problems in the code, but also serve as a more accurate document of the code. It also plays a very important role in the process of continuous integration. Note the following points when writing testcase:

-Test independence: Only one object is tested at a time to locate the error location. This has two meanings: A testcase, only tests one object; A testmethod, only tests one method in this object.

-Give the test method a proper name.

-The reason for the failure is given in the assert function, for example, asserttrue ("… Shocould be true ",......), To facilitate troubleshooting. In this example, if asserttrue cannot be used, the message is displayed. In JUnit, each assert function has the first parameter, which is the prototype of the function that displays the message when an error occurs.

-Test all possible failures, for example, functions frequently modified in a class. For classes that only contain getter/setter, if they are generated by IDE (such as Eclipse), it is not expected. If it is manually written, it is best to test it.

-The code in setup and teardown should not be related to the test method, but should be globally related. For example, for Methods A and B, the code in setup and teardown should be the code required by both A and B.

-Test code organization: the same package and different directories. In this way, the test code can access the protected variable/method of the tested class to facilitate the compilation of the test code. It facilitates the management of test code and the packaging and release of codes in different directories. An example is as follows:

SRC <= source code root directory

-Com

-Mod1

-Class1

JUnit <= test code root directory

-Com

-Mod1

-Class1Author's blog:Http://blog.csdn.net/legendinfo/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.