1, several related concepts
White box test - treats the test object as an open box, the logical structure and other information inside the program are open to the tester.
Return test - software or environmental repair or correction "re-test", automated test tool is especially useful to this type of test.
Unit test - is a minimum particle size test to test a function or code block. It is generally made by programmers because it needs to know the details of internal programming and encoding.
JUnit - is a Java test framework for the source code to write and run repeatable tests. He is an instance for unit test framework system xUnit (for Java language). Mainly used in white box testing, regression test.
2, unit test overview
2.1, the benefits of unit testing
A. Improve development speed - Test is performed in an automated manner, enhance the performance efficiency of test code.
B, improve software code quality - it uses a small version to be released to integration, which is convenient for people to deactivate. At the same time, the reconstruction concept is introduced, so that the code is cleaner and elastic.
C, lifting system trustworthy - it is a regression test. Support repair or correction "re-test" to ensure the correctness of the code.
2.2, the unit test for objects
A. The process-oriented software development is for the process.
B. Object-oriented software development for objects.
C. You can do class test, function test, interface test (most commonly used in the test class).
2.3, unit test tools and framework
The current most popular unit test tool is a XUnit series framework. It is common to divide within JUnit (Java), CPPUnit (C ), DUnit (PHP), and more depending on the language. The first and most outstanding applications of the test framework are JUnit, which is open from Erich Gamma ("Design Mode" and the founder of Kent Beck (XP (Extreme Programming).
3. TeNit Getting Started Introduction
3.1, JUnit's benefits and JUnit unit testing principles
benefit:
A. You can separate the test code to the product code.
B. Test code for a certain class can be applied to another class with less changes.
C. During the construction of the testers, JUnit and Ant can be implemented in incremental development.
D, JUnit is open source code, which can be carried out in secondary development.
C. It is convenient to expand JUnit.
Writing principles:
A. It is a simplified test. This simplification includes the study of the test framework and the preparation of the actual test unit.
B is to keep the test unit persistence.
C is the use of existing tests to prepare related tests.
3.2, JUnit characteristics
A. Use the assertion method to determine the expected value and the actual value difference, return the Boolean value.
B. Test the drive device uses a common initialization variable or instance.
C, the test package structure is easy to organize and integrate operation.
D, support pattern interaction mode and text interaction mode.
3.3, JUnit frame composition
A. The method of testing the test target and the process of process can be called testcase.
B, the collection of test cases, can accommodate multiple test cases, referred to as TestSuite.
C, the description and record of test results. TestResult.
D. Event monitors during the test process (TestListener).
E, the description of each test method and the expected inconsistent condition, called test failure elements (TestFailure)
F, the error abnormality in JUnit Framework (AssertionFaileDerror).
The JUnit Frame is a typical composite mode: TestSuite can accommodate any object from Test; when the TestSuite object is called, the Run () method of the TestSuite is traversed, and the Run () method is called one by one. (Refer to "programmer" 2003-6). 3.4, JUnit installation and configuration
JUnit installation procedure decomposition:
Download the JUnit package in http://download.sourceforge.net/junit/ and extract the JUnit compression package into a physical directory (for example, C: \junit)
3.8.1
). Record the name of the junit.jar file (for example, C: \junit)
3.8.1
/Junit.jar). Enter the operating system (subject to the Windows 2000 operating system), click "Start Setting Control Panel" in order. Select "System" in the Control Panel option, click "Environment Variable", select "Class-Path" keyword (not case sensitive) in the "Variable" list box of "System Variable", if the keyword does not exist Add to. Double click on "Class-Path" keyword Add String "C: \junit
3.8.1
/Junti.jar "(Note, if there are other strings, please add a semicolon"; ") in the character end of the string, this is determined that the modified JUnit can be applied in the integrated environment. For the IDE environment, For items that need to use JUnit to the LIB, they set different IDEs with different settings.
3.5, interfaces and classes commonly used in JUnit
TEST interface - run test and collect test results
The TEST interface uses the Composite design mode, which is a common interface for SISTCASE, aggregate test mode (TestSuite) and test extension (TestDecorator). Its public int countTestCases () method, it comes to count how many TestCase this test, and another method is public void run (testResult), and TestResult is an instance acceptance test results, and the RUN method performs this test.
TestCase Abstract Class - Defining Testing Method
TestCase is an abstract implementation of the Test interface, (cannot be instantiated, can only be inherited) Creating a test instance based on the input test name Name based on the input test name NAME. Since every TestCase has a name when it is created, if a test fails, it can identify which test failed. Setup (), Teardown () method included in the TestCase class. Setup () method centralizes all variables and instances required for initialization test, and execute the setup () method again before each test method in the test class session. The Teardown () method is to release the variables and instances referenced in the test program method after each test method. When developers write test cases, just inherit TestCase, to complete the RUN method, then JUnit get the test case, execute its RUN method, record the test results in TestResult.
ASSERT Static Class - Collection of a series of assertion methods
Assert contains a set of static test methods for the expectation value and actual value comparison, that is, the test fails, the Assertion class will throw an AssertionFaileDError exception, the JUnit test framework will be classified into Failes and record, The logo is not tested. If you specify a String type in this method, this parameter will be made as an ASSERTIONFAILEDERROR anomalous identification information, telling the test personnel to change the exception. JUnit provides a 6-class 31 set method, including basic assertions, digital assertions, character assertions, Boolean words, object assertions. Where the insenrtequals (object expcted, object actual) internal logic determines that uses the equals () method, which indicates whether the internal hash value of the two instances is equal, it is preferred to compare the value of the corresponding class instance. The internal logic of Assertsame (Object Expected, Object Actual) uses the Java operator "==", indicating that the assertion determines whether the two instances come from the same reference (Reference), preferably use this method to different class instances The value is compared. Asserequals (String Message, String Expected, String Actual) This method logic comparison for two strings, and if you do not match, there is a difference in two strings. The ComparisonFailure class provides a comparison of two strings, and the detailed difference characters are given without match. TestSuite test package - a combination of multiple tests
The TestSuite class is responsible for assembling multiple Test Cases. The class to be measured may include multiple tests of the tested class, while TestSuit is responsible for collecting these tests, allowing us to complete all of the tests that are tested in one test. The TestSuite class implements the TEST interface and can contain other Testsuites. It can handle all thrown exceptions when adding TEST. TestSuite handles test cases have 6 stations (otherwise it will be rejected)
A Test case must be a public class (public)
B Test case must inherit and Testcase class
The test method of the C test case must be public (public)
D Test method of test case must be declared as Void
E Test case predetermined noun must be TEST
F Test method in the test case, misunderstand parameters
n TestResult results class and other classes and interfaces
The TestResult result class collects arbitrary test accumulation results, transmitting a RUN () method for each test through the TestResult instance. TestResult is executing TestCase if the failure will throw the TestListener interface is an event listening, which is available for Testrunner class. It informs the object related events of Listener, including testing start StartTest (Test Test), test ending endtest (test test), error, increase exception Adderror (Test Test, throwable T) and increasing failed AddFail: TestFailure The failure class is a "failed" collection class that explains the abnormal conditions that occur during each test implementation. Its TSTRING () method returns a brief description of the "failure" situation
3.6, JUnit An instance
Simple examples in the console are as follows: 1. Write a Triangle class to be tested, create a subclass of Testcase, EXAMPletest: 2, write one or more test methods in ExampleTest, assert the desired result (note: Test as Test The beginning of the method, so that these methods can be automatically founded and tested) 3, written in ExampleTest, which uses reflex dynamics to create a test kit containing all TestXxxx methods: 4, ExampleTest can write setup (), Teardown () method to facilitate all variables and examples required to test or destroy the test at the time of test. (Not required) 5, write a main () method to function testing in a text runner or other GUI
6, compile ExampleTest, execute the test.
3.7, use of JUnit in Eclipse
Eclipse comes with a JUnit plug-in without installation, you can start testing related classes in your project, and you can debug your test case and the test class.
The steps are as follows:
1. Create a test case, click "File-> New-> Other ... menu item, select" Java-> Junit "in the" New "dialog box pop-up, go to" New Junit Testcase " Dialog
2, fill in the corresponding column in the "New Junit Testcase" dialog, mainly Name (test case name), SuperClass (Test's superclass is generally the default junit.framework.testcase), Class Under Test (Terminal) Source Folder (Test Catalog Saved Directory), Package (Test Sample Package Name), and whether main, setup, teardown method is automatically generated.
3, if you click on the "Next>" button, you can also check the method of the test class you want to test, Eclipse will automatically generate the test method corresponding to the selected method, click "Fishish" button a test case Just create it.
4. After writing to complete your test case, click the "Run" button to see the run results.
3.8, JUnit extension application
The following columns have some JUnit extension applications:
JUnit httpunit = web function test tool junit hansel = code overlay test tool junit abbot = interface automatic playback test tool JUnit DBUnit = Database Test Tool JUnit JunitPerf = Performance Tools
3.9, some use JUnit experience
Do not initialize the constructor of TestCase, and use 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. 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. Test class and test methods 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. References and accessories
1. http: // www.junit.org junit official website
2. Test forum for http://bbs.51cmm.com
3. Http://www.uml.org.cn software test column
4. Unit test "programmer" 2002 7
5. JUnit Design Mode Analysis "Programmer" 2003 6
6. Software Test and JUnit Practice
7. Attachment Triangle.java A class to be tested
8. Annex ExampleTest.java A test case class
Triangle.java
/ **
* this is Triangle Class
* @Author liujun
* /
Public Class Triangle
{
/ / Define the three sides of the triangle
Protected long lbordera = 0;
Protected long lborderb = 0;
protected long lborderc = 0;
//Constructor
Public Triangle (long lbordera, long lborderb, long lborderc)
{
THIS.LBORDERA = LBORDERA;
THIS.LBORDERB = LBORDERB;
THIS.LBORDERC = LBORDERC;
}
/ **
* Judgment is a triangle
* Is returning Ture; not return false
* /
Public Boolean Istriangle (Triangle Triangle)
{
Boolean istrue = false;
/ / Judgment the boundary, more than 0 less than 200, the outcrown returns FALSE
IF ((Triangle.lbordera> 0 && Triangle.lbordera <200)
&& (Triangle.lborderb> 0 && Triangle.lborderb <200)
&& (Triangle.lborderc> 0 && Triangle.lborderc <200)))
{
/ / Judgment two and greater than the third side
IF ((Triangle.lbordera <(Triangle.lborderb Triangle.lborderc))
&& (Triangle.lbordeerb <(Triangle.lbordera Triangle.lborderc))
&& (Triangle.lbordeerc <(Triangle.lbordera Triangle.lborderb)))) istrue = true;
}
Return istrue;
}
/ **
* Judgment Triangle Type
* Waist triangle returns a string "equal waist triangle";
* Isometric triangle return string "equidistant triangle";
* Other triangles return string "Do not equipped with triangles";
* /
Public String Istype (Triangle Triangle)
{
String string start = "";
/ / Judgment is a triangle
this.istriangle (Triangle))
{
/ / Judgment is the equilateral triangle IF (Triangle.lbordera == Triangle.lborderb && Triangle.lborderb == Triangle.lborderc)
Strtype = "Isothermal triangle";
/ / Judgment is an inequal triangle
Else IF (Triangle.lbordera! = triangle.lborderb) &&
(Triangle.lborderb! = triangle.lborderc) &&
(Triangle.lbordera! = triangle.lborderc)))
Strtype = "Do not equipped with triangles";
Else
Strtype = "Isometric triangle";
}
Return straTrtype;
}
}
Exampletest.java
Import junit.framework. *;
/ **
* Some tests.
*
* /
Public class exampletest extends Testcase {
Public Triangle Triangle;
//initialization
protected void setup () {
Triangle = New Triangle (10, 2, 9);
}
Public static test suite () {
Return New TestSuite (Exampletest.class);
}
// Function Istriangle () test case
Public void testismLe () {
Asserttrians (Triangle.Istrungle (Triangle);
}
// Function IStype () test case
Public void testiSType ()
{
Assertequals ("Test", Triangle.ITYPE (TRIANGLE), "No Equal Triangle");
}
// Execute test
Public static void main (String [] args) {
// Text method
Junit.textui.teStrunner.run (Suite ());
// swingui method
///junit.swingui.teestrunner.run(Suite (). getClass ());
// AWTUI mode
//junit.awtui.teestrunner.run(Suite (). getclass ());
}
}