Junit is a regression test framework written by Erich Gamma and Kent Beck for Java developers to write unit tests.
1. Overview JUnit test is a programmer test, that is, the so-called white box test, because the programmer knows how the software is tested (how) completes the function and what is done. JUnit is essentially a set of frames, which developers have developed a set of frames. Follow this Article. The frame box requests to write test code. If you inherit a class, you can use JUnit to automatically test it. Since JUnit is relatively independent of the code written by the code, you can test the code to write the code, the implementation of the Test First Design of the XP is a ready-made means: use junit write test code, real current code, run test , Test failed, modify the code, and then run the test until the test is successful. After the modification and optimization of the code, the operation test is successful, and the modification is successful. TEAM development under Java, using CVS (version control) Ant (Project Management) JUnit mode, through the configuration of Ant, test automation can be simply implemented.
For different nature of the subject, such as Class, JSP, Servlet, EJB, etc., JUnit has different skills, and slowly explain. The following uses Class test as an example, unless otherwise specified.
2, download and install
Go to the JUnit Home Download the latest version 3.8.1 Package JUnit-3.8.1.zip Using Winzip or Unzip to extract junit-3.8.1.zip to a directory name to $ Junithome will join JUnit.jar and $ Junithome / JUnit In ClassPath, join the latter only because the test routine is in that directory. Be careful not to run the junit.jar in the JDK's extension directory run command, as shown in the right.
Java junit.swingui.teestrunner junit.samples.alltests
3, the JUnit Architecture The following is an example of Money as an example.
Public class mother {
PRIVATE INT FAMOUNT; // balance
Private string fcurrency; // Type
PUBLIC MONEY (Int Amount, String Currency) {FAMOUNT = Amount; Fcurrency = CURRENCY;
Public int Amount () {RETURN FAMOUNT;
Public string currency () {RETURN FCURRENCY;} PUBLIC MONEY Add (Money M) {// Add money Return New Money (Amount () m.amount (), currency ());} public boolean equals (Object Anobject) { / / Judgment if the amount of money is equal to if (anobject instanceof money) {Money amoney = (Money) Anobject; returncy (currency ()) && amount () == amoney.amount () () == amoney.amount ();} returnif }} Junit itself is around two
Design mode is designed:
Command mode and
Integrated mode.
Command mode uses TestCase to define a subclass, generate an object being tested in this subclass, write code to detect a certain
The method of being called after calling the object is consistent with the expected state, thereby
The assertion code is a bug.
When this subclass is tested, not only one
When implementing the code, you can build it first.
The test basis allows these tests to run on the same basis, and on the one hand, the initialization of each test can be reduced, and the connection between these different methods can be tested.
For example, we have to test Money's Add method, as follows:
Public Class MoneyTest Extends Testcase {/////
Subcound of Testcase
Public void testAdd () {//
Place the test code in TestAdd
Money M12CHF = New Money (12, "CHF"); //
The Bank and the next line are initialized
Money M14CHF = New Money (14, "CHF");
Money expertted = new Money (26, "chf"); //
Expected result
Money Result = M12CHF.Add (M14CHF); //
Run the test
AskERT.ASSERTTRUE (Expected.equals (Result)); //
Judging whether the operation result is the same as expected
}
}
If you test the Equals method, use similar code as follows:
Public Class MoneyTest Extends Testcase {/////
Subcound of Testcase
Public void testequals () {//
Place the test code in TESTEQUALS
Money M12CHF = New Money (12, "CHF"); //
The Bank and the next line are initialized
Money M14CHF = New Money (14, "CHF");
AskERT.ASSERTTRUE (! M12chf.equals (null)); // Test assert.assertequals (M12CHF, M12CHF) (M12CHF, New Money (12, "CHF") (12, "CHF")); // (1 ") ), (! M12chf.equals);}}
When testing the Add and Equals methods simultaneously, their respective initialization work, combined into together, form a test basis, initialized with setup, and clear it with Teardown. As follows: Public class moneytest extends testcase {////////
Subcound of Testcase
Private Money F12CHF; //
Extract common object
PRIVATE MONEY F14CHF;
Protected void setup () {// Initialization public object F12CHF = New Money (12, "chaf"); f14chf = new Money (14, "chalk");} public void test () {// Test the correctness of the equals method AskERT.ASSERTTRUE (! F12chf.equals (null); assert.assertequals (F12CHF, F12CHF); Assert.assertequals (F12CHF, New Money (12, "CHF")); askERT.ASSERTTRUE (! F12chf.equals (f14chf) } Public void testsimpleadd () {// Test the correctness of the add method Money expected = new Money (26, "chf"); Money Result = F12chf.Add (f14chf); assert.equals (result) }}
Save any of the TestCase subclauses in the above three to files named Moneytest.java and increased in the file first line
Import junit.framework. *;
It can be running. The problem with JUnit is very interesting, and below will be explained.
The above is the Interpretation Concept "FixTure", introduced two tests for two methods. The essential difference between command mode and integration model is that the former only runs a test at a time.
Integration Mode With TestSuite to run all Test *** () methods in a TestCase subclass, you can also include a TestSuite subclass, thereby beingcomes a level relationship. You can treat TestSuite as a container, which can be placed in TestCase, and it can nested themselves. This architecture is very similar to the current situation of step-by-step integration. For the example above, there is code as follows:
Subclass for Public Class Moneytest Extends Testcase {// Testcase
....
Public Static Test Suite () {//
Static Test
Testsuite Suite = new testsuite (); //
Generate a TestSuite
Suite.Addtest (New Moneytest ("Testequals")); //
Add test method
Suite.Addtest (New Moneytest ("TestsImpleAdd"));
Return suite;
}
}
Starting from JUnit 2.0, there is a simple method:
Subclass for Public Class Moneytest Extends Testcase {// Testcase
....
Public static test suite () {
Static Test
Return New TestSuite (Moneytest.class); // Troubled
}
}
TestSuite sees an esstopic example in the following applications.
4. The test code is run first, say the most commonly used integrated mode. After the test code is written, you can write the main method in the corresponding class, run directly with the java command; or you may not write the main method, run with the runner provided by JUnit. Junit provides three runners of TextUI, AWTUI and Swingui. Take allTests operation as an example in the first step in the first step, there are four types:
Java junit.textui.teestrunner junit.samples.alltests
Java junit.awtui.teestrunner junit.samples.alltests
Java junit.swingui.teestrunner junit.samples.alltests
Java junit.samples.alltests
The main method is generally simply called Suite (), when there is no main, Testrunner generates a TestSuite as a parameter to run the class.
There are two ways to run the command mode.
Static method
Testcase test = new Moneytest ("Simple Add") {
Public void runtest () {
TestsimpleAdd ();
}
}
Dynamic method
Testcase test = new Moneytest ("testsimpleadd");
I tried it,
It seems to have problems, which friend is successful, please give me a view. It is indeed possible.
Import junit.framework. *;
public class MoneyTest extends TestCase {// TestCase subclass private Money f12CHF; // common object extraction private Money f14CHF; public MoneyTest (String name) {super (name);} protected void setUp () {// Initialization Common Object F12CHF = New Money (12, "CHF"); F14CHF = New Money (14, "CHF");} public void test () {// Test the correctness of the Equals method Assert.asserttrue (! f12chf.equals (null) ); Assert.assertequals (F12CHF, F12CHF); Assert.assertequals (F12CHF, New Money (12, "CHF")); assert.asserttrue (! F12chf.equals (f14chf));} public void testAdd () {///// Test the correctness of the add method Money expected = new Money (26, "chf"); Money Result = F12chf.Add (f14chf); assert.asserttrue (Expected.Equals (result));} // public static void main (String [] Args) {// TestCase test = new MoneyTest ("Simple Add") {// money void runtest () {// TestAdd (); //} //}; // junit.textui.teestrunner.run Test); //} Public STA Tic void main (string [] args) {testcase test = new Moneytest ("testadd"); junit.textui.teestrunner.run (test);}} gives an example of integrated testing with a static method:
Public static test suite () {
Testsuite suite = new testsuite ();
Suite.addtest
New testcar ("getWheels") {
Protected void runtest () {testGetWheels ();
}
);
Suite.addtest (New TestCar ("GetSeats") {protected void runtest () {testgetseats ();}});}});}}
5, application case
The JUnit Primer routine is running as follows:
Java com.hedong.junitlearning.primer.shoppingCartTest
Ant JUnit Mailto realizes automatic compile, debugging, and sending the result of Build.xml Junit implementation, great writing, and understanding. The routine is running as follows:
Java com.hedong.junitlearning.car.testcarnojunitjava junit.swingui.teestrunner com.hedong.junitlearning.car.testcar
JUnit combined with log4j, the routine of the dish is running:
CD ACAI
Ant junit
6, some problems
Some people summed out some very valuable use skills on the basis of practice, I have not passed one by one "test", and it is temporarily here.
Do not initialize FixTure with the constructor of TestCase, and use the setup () and Teardown () methods. Do not rely on or assume the order of test operation, because JUnit uses the Vector saved test method. So different platforms will take out test methods from the vector in different orders. I don't know if it is true in 3.8, but it provides an example of which is specified by vectorsuite, if not specified? Avoid writing TestCase with side effects. For example: If the subsequent test depends on some specific transaction data, it is not necessary to submit transaction data. Simple rollback is ok. When inheriting a test class, remember to call the setup () and teardown () methods of the parent class. Place the test code and work code together and compile and update synchronize. (Tesk for JUnit in Ant should have a consistent naming scheme. To form a test class name as before the work class is preceded. Make sure the test is not related to time, do not rely on the use of expired data for testing. It is difficult to reproduce the test during subsequent maintenance. If you have written the software to the international market, you should consider international factors when writing tests. Don't test only with the mother tongue Locale. Use JUnit to provide an Assert / Fail method as well as an abnormal process, you can make the code more concise. Test should be as small as possible and perform fast. Built the test program in the same package as the subject to avoid the test code in your original code directory, you can put the test code in a source mirror directory containing a TestSuite test class in its own application package.
7, related resources download
The following jar package, I just made the work of packaging, compiling and debugging, for downloading learning, the relevant rights belonging to the original author.
Running routines. Jar build.xml A cuisine routines JUnit API Han translation (PDF)
8, unfinished task
HTTPUNIT CACTUS Tests JUnit with link pool
main reference: