JUnit Basics Tutorial

Source: Internet
Author: User
Tags assert function prototype

Content Summary:

On the project name to use JUnit, click Properties--java Build path-libraries and click Add External JARs to put the JUnit package on the line. and create a new junit test case on the project that needs to be tested

JUnit is the framework for writing unit Test in Java, and some of the most popular unit test tools are now extended on JUnit.

Configuring JUnit in Eclipse

On the project name to use JUnit, click Properties--java Build path-libraries and click Add External JARs to put the JUnit package on the line. And in the need to test the

Usage

1. Basic use steps, JUnit is very simple to use, its basic use of the steps:

-Create, derive from Junit.framework.TestCase the test case required by the Unit test

-Write a test method that provides a test method similar to the following function signature:

public void testxxxxx ();

-Compile and write test case class after writing

-run, start JUnit Test Runner, to run this test case.

JUnit provides 2 basic test Runner: A character interface and a graphical interface. The start commands are as follows:

A graphical interface:

Java Junit.swingui.TestRunner XXXXX

b Character Interface:

Java Junit.textui.TestRunner XXXXX

2. Examples of use:

Import Junit.frmework.TestCase;

public class Testsample extends testcaset{

public void TestMethod1 () {

Asserttrue (TRUE);

}

}

3. Setup and teardown, these two functions are provided in the JUnit framework to initialize and reverse-initialize each test method.

Setup is called before each test method call and is responsible for initializing the test environment required by the test method;

Teardown is invoked after each test method is invoked and is responsible for undoing the test environment. Their relationship to the test method can be described as follows:

Test started-> setUp-> testxxxx-> teardown-> test ended

4. Examples of use:

Import Junit.frmework.TestCase;

public class Testsample extends testcaset{

protected void SetUp () {

Initialize .....

}

public void TestMethod1 () {

Asserttrue (TRUE);

}

potected void Teardown () {

Undo initialization ...

}

}

5. Distinguish fail, exception.

-fail, expectation of errors. Reason: Assert function error (such as Assertfalse (true));

Fail function generation (e.g. fail (...) )。

-Exception, the error that is not expected to occur, belongs to the exception that is thrown when the unit test program runs.

It and the runtime exception thrown during normal code runs are of one type.

For functions such as Assert, fail, and so on, see JUnit's Javadoc.

6. Examples of use:

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."); Impossible to reach

}catch (Exception e) {

Fail ("Yes, I catch U"); We should get there.

}

......

}

potected void Teardown () {

Undo initialization ...

}

}

7. Assemble Testsuite and run more test. In JUnit, the composiste pattern is composed of Test, TestCase, and Testsuite.

By assembling your own testsuite, you can complete calls to all testcase that are added to this testsuite.

And the testsuite of these definitions can also be assembled into larger testsuite, which at the same time facilitates the management of the ever-increasing testcase

and maintenance.

Another advantage of this is that it can be invoked from any node (testsuite or testcase) of this testcase tree.

To complete the invocation of all testcase below this node. Increases the flexibility of unit test.

8. Examples of Use:

Import Junit.framework.Test;

Import Junit.framework.TestSuite;

public class testall{

public class testall{

Defining a suite, the role of JUnit can be seen as a Java application-like main.

public static Test Suite () {

TestSuite Suite = new TestSuite ("Running all Tests.");

Suite.addtestsuite (Testcase1.class);

Suite.addtestsuite (Testcase2.class);

return suite;

}

}

Run is the same as running a separate testcase, see Step 1 "Run".

9. Use the Ant junit task. In addition to using Java to run JUnit directly, we can also use the JUnit task provided by JUnit

Run in conjunction with Ant. Several of the main ant tasks involved are as follows:

-<junit>, defining a JUnit task

-<batchtest>, located in <junit>, running multiple testcase

-<test>, in <junit>, running a single testcase

-<formatter>, in <junit>, define a test result output format

-<junitreport>, define a junitreport task

-<report>, located in <junitreport>, output a JUnit

See related documentation for specific syntax.

10. Examples of Use:

<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>

Check table

The use of JUnit is not difficult, but it is not easy to write a good testcase. A bad testcase is often both a waste of time and a

The actual role. On the contrary, a good testcase can not only well point out the problems in the code,

It can also be a more accurate document for your code, while still

-Test independence: Test only one object at a time to easily locate the wrong location. This has 2 layers of meaning: a testcase,

Test only one object, one TestMethod, only one method in this object.

-Give the test method a proper name.

-Gives the reason for failure in the Assert function, such as: Asserttrue ("... should be true", ...) for easy error checking.

In this example, if the asserttrue is not passed, the given message will be displayed. In JUnit, each assert function has a

The first parameter is the function prototype that displays the message when an error occurs.

-Test all possible failures, such as a function that changes frequently in a class. For those classes that only contain getter/setter,

If it is generated by the IDE (such as Eclipse), it can be an accident; if it is written manually, then it is best to test it.

-code in Setup and teardown should not be related to test methods, but should be global. As with test methods A and B,

The code in Setup and teardown should be the code needed for both A and B.

-Organization of the test code: same package, different directory. In this way, the test code can access the protected variable/method of the tested class.

Facilitate the writing of test code. In different directories, it facilitates the management of test code and the packaging and distribution of code. One example is as follows:

src <= Source Code root directory

|---com

|---mod1

|---Class1

JUnit <= test Code root directory

|---com

|---mod1

|---Class1

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.