JUnit learning notes (reproduced)
Contributor Huson submission date 2004-12-20 01:27 PM
Author: hedong JUnit was written by Erich Gamma and Kent Beck a regression testing framework (regression testing framework), for Java developers to write unit testing. 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 installation ¨ Go to the JUnit Home Download the latest version 3.8.1 Package JUnit-3.8.1.zip ¨ Use Winzip or Unzip to extract junit-3.8.1.zip to a directory name $ junithome ¨ Take JUnit. JAR and $ JUNITHOME / JUnit Add to ClassPath and join the latter only because the test routine is in that directory. ¨ 注意 Be careful not to put junit.jar in the jdk's extension directory ¨ Run command, as shown on the right. Java junit.swingui.teestrunner junit.samples.alltests 3, under the JUnit Architecture as an example for Money.
public class Money {private int fAmount; // balance private String fCurrency; // currency 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 () m.amount (), currency ());} public boolean equals (Object Anobject) {////////////////////////////////////////////////////////// Determine if the amount of money is equal to if (anobject instanceof money) {Money amoney = (Money) anobject; return amoney.currency (). Equals ()) && amount () == amoney.amount ();} Return False; } Junit itself is designed around two design patterns: command mode and integration mode. · Command mode defines a subclass with TestCase, generates a test object in this subclass, writing code detection, a method is called The status of the rear object is consistent with the expected state, and the assertion code is bug. When this subclass is tested to implement code, you can establish a test basis first, let these tests run on the same basis, and the initialization of each test can be reduced, and the connection between these different methods can be tested. .
For example, we want to test Money's Add method, as follows: Public class MoneyTest Extends Testcase {// Testcase Sub-class Public Void TestAdd () {// Put the test code in TestAdd Money M12chf = New Money (12, "CHF "); // Bank and the next line to initialize some of the initialization MONEY M14CHF = New Money (14," CHF "); Money Expected = New Money (26," CHF "); // Expected results Money Result = m12chf.Add (M14CHF); // Run the test method assert.asserttrue (Expected.equals (result)); // Judgment whether the result is the same with expected}} If you test the equals method, use similar code, as follows: Public class MoneyTest Extends Testcase {// Testcase Sub-class public void test () {// put the test code in TESTEQUALS MONEY M12CHF = New Money (12, "CHF"); // The Bank and the next line for some initialization MONEY M14CHF = New Money (14, "CHF"); assert.asserttrue (! m12chf.equals (null)); // Test Assert.assertequals (M12CHF, M12CHF); Assert.assertequals (M12CHF, New Money (12) , "CHF")); // (1) Assert.asserttrue (! M12chf.equals (m14chf));}} When testing the Add and Equals methods simultaneously, you can combine their respective initialization, merge together Perform, form a test basis, initialized with setup, and clear it with TEARDOWN. As follows: Public class MoneyTest Extends TestCase {// Testcase Sub-class Private Money F12CHF; / / Extract Public Object Private Money F14CHF; protected void setup () {// Initialization public 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); AskERT.ASSERTEQUALS (F12CHF, New Money (12, "CHF")); assert.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 three TestCase subclauses in the above three to Moneytest. In the Java file, it adds import junit.framework. *; it can be run.
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. • Integrated Mode Using 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: Public class mothertest extends Testcase {// Testcase subclavation ... PUBLIC TEST Suite () {// Static Test TestSuite Suite = New Testsuite (); // Generate a TestSuite Suite.addtest ("Testequals")); // Add Test Method Suite.addtest ("TestsimpleAdd")); Return Suite;}} Starting from JUnit 2.0, there is a simple method: public class MoneyTest Extends Testcase {// Testcase Subcada .... Public Static Test Suite () {// Static Test Return New TestSuite (MoneyTest.class); // Troubled to Parameters} Testsuite See Establishment Example, There are 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. AllTests to run earlier in step 2 as an example, may be four: java junit.textui.TestRunner junit.samples.AllTests java junit.awtui.TestRunner junit.samples.AllTests java junit.swingui.TestRunner junit.samples.AllTests Java junit.samples.alltests main method is generally simply call Suite (), and when there is no main, Testrunner generates a TestSuite as a parameter to the parameter. For the operation mode, there are two ways . · Static method testcase test = new MoneyTest ("Simple add") {paper void Runtest () {testsimpleadd ();}};, dynamic method Testcase test = new Moneytest ("testsimpleadd"); I tried it, it is indeed.
import junit.framework *;. public class MoneyTest extends TestCase {// private Money f12CHF TestCase subclasses of; // common object extraction private Money f14CHF; public MoneyTest (String name) {super (name);} protected void setUp ( ) {// initialized public object F12CHF = New Money (12, "chaf"); f14chf = new Money (14, "chaf");} 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") {// public void runtest () {// TestAdd (); //} //}; // junit .textui.teestrunner.run (test); //} public static void main (string [] args) {testcase test = new Moneytest ("testadd"); junit.textui.teestrunner.run (test);}} An example of a static method with integrated test: 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 ();}}); Return Suite;} 5, Application Case 1. JUnit Primer routine, running as follows: java com.hedong.junitlearning.primer.ShoppingCartTest 2. Ant Junit Mailto realizes automatic compilation, debugging And the result of the result of Build.xml 3. JUnit is implemented, it is very good, and it is also profound.
The routine is running as follows: java com.hedong.junitlearning.car.testcarnojunit java junit.swingui.teestrunner com.hedong.junitlearning.car.testcar 4. JUnit and log4j combined, A cd Ant Junit 6, Some problems have summed up some very valuable use skills on the basis of practice, I have not passed one "test", and temporarily list here. 1. Do not initialize FixTure with the constructor of TestCase, and use the setup () and Teardown () methods. 2. Do not rely or assume the order of test run, because JUnit uses the Vector Save 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? 3. 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. 4. When inheriting a test class, remember to call the SETUP () and Teardown () method of the parent class. 5. Place the test code and work code together and compile and update synchronously. (Task for JUnit is supported in Ant 6. The test class and test method should have a consistent naming scheme. To form a test class name as before the work class is preceded. 7. 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. 8. If you write software to the international market, you should consider international factors when preparing tests. Don't test only with the mother tongue Locale. 9. Use JUnit to provide an ASSERT / FAIL method as much as possible, and the code can be more concise. 10. Test should be as small as possible and perform fast. 11. Set the test program in the same package as the subject to the subject 12. Avoid the test code in your original code directory, you can put the test code in a source mirror directory 13. In your own application package contains one TestSuite Test Class 7, related resources to download the following jar package, I just made the work of packaging, compiling and debugging, for downloading learning, the relevant rights belong to the original author.