1, JUnit definition
=========
JUnit is an open source java testing framework used to write and run repeatable tests.
To put it bluntly, Junit is an integrated test tool that can automate the test.
Here is the unit test: a white box test belonging to the software engineering, which is the function of testing a certain approach to a class.
2, JUnit test ideology
============
If you want to write a code:
Write test with JUnit, then write code
Write code, run test, test failure
Modify the code, run the test until the test is successful
Test First Design, which is respected in XP is based on the above technology.
However, it seems that it is not active. The following HelloWorldtest is an example. If there is no HelloWorld.class exists, it is compiled to helloworld world = new helloworld (); it will be an error.
Is this about the thought of "writing test, after writing code"?
3, "write test, write code"
================
a) Forced you to consider a class of features first, that is, this class provides an external interface, not too early
Facing it into the details. This is a design principle that is advocated.
b) Good test is actually a good document. This type of user can often understand its functionality by viewing the test code of this class. Special, if you get a program of others, write testing is the best way to understand the functionality of this program. The principle of XP is Make IT Simple, not recommended to write another document, because the project is often changed during the development process, if the document is written in the early stage, there is a synchronization document after the code changes, more work, and due to project time The incomplete or inconsistent with the document is inconsistent with the code, and it is better not to write. And if you write a document after the project, developers often have forgotten all kinds of considerations when writing code, and there is a pressure of the next project, and managers are not willing to write documents for the old project. Problems leading to future maintenance.
c) No one can guarantee that the demand is not changed, and the past projects often have a big headache for the changes in demand, and this change will bring other places. To this end, in addition to the design of the design to split items (loosely coupled), but if there is a test, a good test framework has been established, and the change is modified, if the code is modified, just re-run the test code, if The test passed, but also guaranteed the success of the modification. If there is an error in the test, it will immediately find that the wrong is wrong. Modify the appropriate part and run the test until the test is fully passed.
4, Team Development and Development Mode under Java
================== Generally adopt CVS (version control) Ant (project management) JUnit (integrated test) mode:
Go to work every morning, each developer gets a copy of the entire project from CVS Server.
Get your own task, first write the test code for today's task.
Then write the code of today's task, run the test until the test passes, the task is completed
One or two hours before get off work, each developer submitted the task to CVS Server
Then run automatic testing throughout the project, which test is wrong, find the relevant personnel to modify until all tests are passed. Get off work ...
5, how to install?
=======
1. Download the latest JUnit at http://www.junit.org/, I downloaded JUnit3.8.1.zip.
2. Unzip the downloaded compression package to the installation directory, I installed D: /junit 3.8.1.
3. Add JUnit.jar in the installation directory to ClassApth, which is successful.
6. How do I test run normal?
===========
1. Type in D: /Juni3.8.1/junit/samples/ directory
Java -classpath% classpath% ;. junit.textui.teStrunner SimpleTestSt
If the following information appears:
.
Time: 0.01
OK (1 test)
Then indicate successful installation.
It is also possible to test the Graphics method:
Java -classpath% classpath% ;. junit.swingui.teStrunner SimpleTest
2, or write an example to test:
a) Type the following code into the editor and save it as SimpleTest.java.
Import junit.framework.testcase;
Public class simpletest extends testcase {
Public SimpleTest (String Name) {
Super (Name);
}
Public void testTest () {
Asserttrue (TRUE);
}
}
b) Compilation Simpletest.java
Javac -d. -classpath% classpath% Simpletest.java
c) Run SimpleTest
Java-ClassPath% classpath% ;. SimpleTest
7. Some major organizational structures in junit.jar
=====================
Junit.framework.assert
.Assertionfailederror
.Comparisonfailure
.Protectable
.Test
.Testcase
.Testfailure
.Testlistener.testresultresult
.Testsuite
Junit.textui.Resultprinter
.TESTRUNNER
Junit.swingui.aboutdialog
.Counterpanel
.DefaultfailuredetailView
.Failurerunview
.Progressbar
.Statusline
.TESTHIERARCHYRUNVIEW
.TestrunContext
.TESTRUNNER
.TESTRUNVIEW
.Testselector
.Testsuitepanel
.Testtreemodel
8. Basic steps to write test classes
=============
The general step of writing test code using JUnit is:
(1) Introduce the JUnit frame package. Import junit.framework. *.
(2) Define the test class name, which is generally attached to Test after the class name to be tested.
(3) Test class inherit the TestCase class of JUnit.
(4) Implementing the construction method of the class, you can simply call the super (name) in the construction method.
(5) Implement the main () method of the class, simply call JUnit.Textui.Testrunner.Run (SimpleTest.class) in the main () method to specify the execution test class.
(6) Heavy Duty Setup () and Teardown () methods, setup () methods are used to perform an initialization of the environment when performing each test case.
(For example, open database connections), the Teardown () method is used to perform each test case-by-case clear environment (such as turning off the database connection).
(7) Write each test case, write some TestXxxxx () method (Test before the method to test).
9. How to create a test case (example)?
================
The complete code framework of the test class is as follows:
Import junit.framework. *;
Public class helloworldtest extends Testcase {
/ **
* Constructor
* /
Public HelloWorldTest (String Name) {
Super (Name);
}
/ **
* Main method
* /
Public static void main (string args []) {
JUnit.textui.teStrunner.run (HelloWorldtest.class);
}
/ **
* Initialization before testing -> Execute the setup () method, initialize any value you need
* /
protected void setup () {
}
/ **
* Clear the test environment ---> Call Teardown (), cancel the initialization and go to the next test
* /
protected void teardown () {
}
/ **
* Test case 1
* /
Public void testsayhello () {
HelloWorld World = New HelloWorld ();
// assert (world! = null); Assertequals ("Hello World", World.SAYHELLO ());
}
}
Javac -d. -classpath% classpath% HelloWorldtest.java
Java -classpath% classpath% ;. HelloWorldtest
-------------------------------------------------- ------------------
/ *
* HelloWorld.java
* /
Class helloworld {
Public String Sayhello () {
Return "Hello World";
}
Public static void main (String [] args) {
HelloWorld World = New HelloWorld ();
System.out.println (World.SAYHELLO ());
}
}
Javac -d. HelloWorld.java
-------------------------------------------------- ------------------
Return "Hello World" in HelloWorld.java; this is Return "Hello Worl!"; Try to see what tips will appear.
10, what is test suit?
The test bag is actually the test collection that should be performed in the same session.
The test package performs the test organization together without instead of whether the test is in the same file.
Listing A shows our test package contains two tests:
Listing A: Test Suite
Public static test suite () {
Testsuite suite = new testsuite ();
Suite.Addtest (New XMLTest ("TestPersoncount"));
Suite.Addtest (New Xmltest ("TestContainSperson");
Return suite;
}
11. How do I use the test package to perform a test?
Perform testing needs to create an executable class to call the JUnit test runner. Runner is responsible for performing test packages, running all tests and outputs test results.
List B shows how to integrate the test package into the test runner:
Listing B: XmlteStrunner.java
Import junit.framework.test;
Import junit.framework.testsuite;
Import Xmltest;
Public class xmlteestrunner {
// public static test suite () {
// TestSuite Suite = new testsuite ();
// suite.addtest (New XMLTest ("TestPersonCount");
// suite.addtest (New Xmltest ("TestContainSperson");
// Return Suite;
//}
/ **
* Show how to pass the name of the class to the test package constructor from moving loading test.
* /
Public static test suite () {
Return New TestSuite (XMLTest.class);
}
Public static void main (string [] args) {junit.textui.teestrunner.run (suite ());
}
}
12, how to create a test package? - Handmade creation and automatic creation
=====================================================================================================================================================
/ **
* Manually created:
* Below this simple test runner is responsible for creating a test package, first add each test and add the entire test package.
* /
Import junit.framework.test;
Import junit.framework.testsuite;
Public class testrunner {
Public static testsuite suite () {
Testsuite T = New Testsuite ();
T. Addtest (New HelloWorldTest ("Testsayhello");
T.AddTest (New SimpleTest ("TestTest");
T.AddTestSuite (Testrunner.class);
Return T;
}
Public static void main (string args []) {
Junit.textui.teStrunner.run (Suite ());
}
}
Run: java -classpath% classpath%; Testrunner
(My Testrunner.class is placed in the TEST directory with TEST)
/ **
* Automatic creation:
* Read the test directory from the command line, traverse the entire directory to find the extension ".class" file, then add them to the test package.
* /
Import junit.framework.test;
Import junit.framework.testsuite;
Import java.lang.classNotfoundException;
Import java.io. *;
Import java.util.vector;
Public class allrunner {
Public Static Void Class_List (File Directory, TestSuite T) {
IF (Directory.IsDirectory ()) {
String [] files = Directory.list ();
For (int i = 0; i File f = new file (Directory, Files [i]); IF (f.isfile () && f.getName (). endswith (". Class")) { INT LEN = f.getname (). Length (); String n = f.getname (). Substring (0, len - 6); Try { T.AddTestSuite (Class.Forname (n)); } catch (java.lang.classnotfoundexception e) { System.out.println (e); } } } } } Public static void main (string args []) { TestSuite T = New Testsuite ("Please enter the directory name" args [0]); allrunner.class_list (new file (args [0]), T); Junit.textui.teStrunner.Run (T); } } Tips: Put all the test cases in a TMP directory, run Java -classpath% classpath%; onrunner ../tmp (My allRunner.class is placed in the Test Test Test Test Test Test Test) For this example, the created test runner runs all the tests in the specified directory and displays the result screen. Of course, the test package we dynamically creates assume that all tests are running and run in order from the directory in alphabetical order. Do not choose the testing of the implementation is also a possible testing requirement, but in this case you can only add the test to the test package. Note: Our test runner (Testrunner) is imported into classes with a Java class load, so the class to be loaded must be in the classpath (so I have added the class directory under D: /J2SDK1.4/Mywork). ClassPath has been went). The output result of the test runner is the test result, because the output is indicated by all the tests in the directory, so this test is very helpful to our development. . 13, how to integrate with ANT? ================ Integrated JUnit's Ant can help us quickly test the system's changes. Jakarta Project creates an integrated JUnit for Ant. These tasks can automatically run tests simultaneously generate output results and reports. 14, how to generate an HTML report ============== 15. How to place a TEST file? ============== Place the original file, but the structure is the same as the package. As follows: SRC COM xyz Someclass.java Test COM xyz Someclass.java