JUnit learning notes

xiaoxiao2021-03-06  63

JUnit learning notes

.skiplink {display: none};

.code {

Background-color: #efefef;

Padding: 5px;

Font-Family: Courier New, Courier, Monospace

FONT-SIZE: 110%;

Margin-bottom: 5px;

Margin-top: 5px;

Margin-left: 10px;

Margin-Right: 10px;

Padding-top: 2px;

Padding-bottom: 2px;

Border: 1px dashed # 999999;

}

INS {

Text-decoration: none;

Color: RED;

}

This article is written by Hilton's copyright belongs to HILTON. Please let us know hitonyang@yahoo.com.cn

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 put JUnit.jar running commands in the EXTENSION directory of the JDK, as shown below.

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 match; // 货 货 类 类

PUBLIC MONEY (Int Amount, String Currency) {FAMOUNT = Amount; Fcurrency = CURRENCY;

Public int adjital;} public string currency;} public money add (Money M) {// Add money return new Money (Amount () m.amount (), currency ()) } Public boolean equals (Object Anobject) {// Judging whether the amount of money is equal to IF (Anobject InstanceOf Money) {Money Amoney = (Money) anobject; returncy ()) && amount () = = Amoney.Amount ();} returnaf false;}}

Junit itself is designed around two design patterns: 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 {// Testcase subclass PUBLIC VOID TESTADD () {// Place the test code in the TestAdd Money M12CHF = New Money (12, "CHF"); // The Bank and the next line are initialized Money M14CHF = New Money (14, "CHF"); Money Expected = New Money (26, "CHF"); // The expected result Money Result = M12CHF.Add (M14CHF); // Run the test method assert. AssertTrue (Expected.equals (result)); / / Judgment whether the result is the same as expected}}

If you test the Equals method, use similar code as follows:

Public Class MoneyTest Extends Testcase {// Testcase subclavab PUBLIC VOID TESTEQUALS () {// Place the test code in TESTEQUALS MONEY M12CHF = New Money (12, "CHF"); // The Bank and the next line of initialization Money M14CHF = New Money (14, "CHF");

AskERT.ASSERTTRUE (! M12chf.equals (null)); // Test assert.assertequals (M12CHF, M12CHF) (M12CHF, New Money (12, "CHF") (12, "CHF")); // (1 ") Assert.asserttrue (! M12chf.equals (m14chf));}} When testing the Add and Equals methods simultaneously, their respective initialization work, combined into together, form a test basis, initialize with setup, with TEARDOWN is clear. 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, "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:

Public Class MoneyTest Extends Testcase {// Testcase Subcada ..... PUBLIC TEST Suite () {// Static Test TestSuite Suite = New Testsuite (); // Generate a TestSuite Suite.Addtest (New Moneytest ("Testequals" ))); // Add test method Suite.addtest ("TestsimpleAdd")); return suite;}} Starting from JUnit 2.0, there is a simple method:

Subcads of Public Class MoneyTest Extends Testcase {// Testcase ... PUBLIC STATIC TEST Suite () {Static Test Return New TestSuite (MoneyTest.class); // That is parameter}}

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.Alltestsjava junit.AWTUI.TESTRunner junit.samples.alltestsjava junit.swingui.teestrunner junit.samples.alltestsjava junit.samples.alltests

The main method is generally simply called Suite (), and when there is no main, Testrunner generates a TestSuite as a parameter in the run 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, as if there is a problem, which friend is successful, please pay pointed to me. 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 routines are 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 Acaiant Junit

6. Some problems have summed up some very valuable use skills on the basis of practice. I have not passed one "test", which 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 belong 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:

JUnit Getting Started http://www.dotspace.twmail.org/test/junit_primer.htm How to use JUnit Framework to write unit tests http://www.chinaUnix.Net/bbsjh/14/546.html Ant Junit log4j CVS for XP mode development http://ejb.cn/modules/tutorials/printpage.php?tid=4 Test web application httpunit Test web application http://www.zdnet.com.cn/developer/code/story TEMITS or JUNIT? Http://www.jdon.com/jive/thread.jsp?forum=16&thread=9156 Ant Junit test automation Biggie (original) http://www.9cbs.net/develop/Article/19\19748.SHTM JUnit embodiment http://www.neweasier.com/article/2002-08-07/1028723459.html JUnitTest Infected: Programmers Love Writing Testshttp: //junit.sourceforge.net/doc/testinfected/testing.htm JUnit Cookbookhttp: / /junit.sourceForge.Net/doc/cookbook/cookbook.htm junit primerhtp://www.itu.dk/~lthorup/junitprimer.html ibm developworkshtp://www 106.ibm.com/search/searchResults.jsp? query = junit & searchScope = dW & searchType = 1 & searchSite = dWChina & pageLang = zh & langEncoding = gb2312 & Search.x = 0 & Search.y = 0 & Search = Search author: Hilton source: http: //hedong.3322.org/

转载请注明原文地址:https://www.9cbs.com/read-113010.html

New Post(0)