|
As software projects increase, software testing becomes more and more important in software development. If the software project does not have a good testing process, as the system grows, both the project management personnel and the software development personnel will lose confidence in the prospects of the project, and may even disagree with the project objectives, because for a long time there has been no effective control over program code and system design, many problems have been temporarily hidden or gradually evolved into other problems. The longer the software development cycle, the more evolved versions of the problem. The final result is "continuous cutting and chaos ".
Unit testing is the most fundamental part of the entire test process. It requires programmers to discover and control problems as early as possible. In addition, they can help diagnose problems in integration testing. This laid a solid foundation for the establishment of an efficient Event Response Mechanism in the software development process.
JUnit provides a framework for Java program developers to implement unit tests, making Java unit tests more standardized and effective, and more conducive to testing integration.
Internal Structure of JUnit
JUnit Software Structure
JUnit has seven packages. The core packages are junit. framework and junit. runner. The Framework Package is responsible for the entire Framework of the test object, and the Runner is responsible for testing the driver.
Class Structure of JUnit
JUnit has four important classes: TestSuite, TestCase, TestResult, and TestRunner. The first three classes belong to the Framework package, and the latter one is different in different environments. The text test environment is used here, So junit. textui. TestRunner is used. The responsibilities of each category are as follows:
1. TestResult is responsible for collecting the results executed by TestCase. It divides the results into two types: predictable Failure and unpredicted Error. It is also responsible for forwarding test results to TestListener (this interface is inherited by TestRunner) for processing;
2. TestRunner, the starting point of the customer object call, is responsible for tracking the entire test process. Displays the returned test results and reports the Test Progress.
3. TestSuite, responsible for packaging and running all TestCase.
4. TestCase: class to be inherited by the customer test class. It initializes the customer class during testing and calls the test method.
There are also two important interfaces: Test and TestListener.
1. Test contains two methods: run () and countTestCases (), which are used to extract Test action features.
2. testListener contains four methods: addError (), addFailure (), startTest (), and endTest (). It processes the test results and extracts the action features of the test-driven process.
The following two class diagrams (limited space, only the main part) illustrate the relationship between classes and the junit design goal (1 ). The class in the test case adopts the Composite mode. In this way, the customer's test object is transformed into a "part-whole" hierarchy. The Customer Code only needs to inherit the TestCase class, and can be easily combined with other existing objects, making unit test integration more convenient.
Figure 1 Test Structure
Figure 2 shows the Test Trace class diagram. Figure 2 TestSuite on the left contains a set of test objects and a test result set on the right. How to deal with the specific results, and what test objects are included, did not draw a conclusion immediately, but tried to delay to the specific implementation. For example, the JUnit that implements the TestListener Interface contains: junit. awtui. testRunner, junit. swingui. testRunner, junit. ui. testRunner and so on, and even the customer uses their own class to implement TestListener, so as to achieve a variety of purposes.
Figure 2 test trail
From the above two class diagrams, you can understand the basic idea of JUnit for unit testing. The core of this framework is the result set and case set.
JUnit implementation process
The typical method to use JUnit is to inherit the testcase class, and then reload some of its important methods: setup (), teardown (), runtest () (these are optional ), finally, these customer objects are assembled into a testsuite object and handed over to JUnit. textui. testrunner. run (case set) driver. The following describes how the case set works.
Figure 3 illustrates the JUnit testing process architecture. We will analyze the graph in detail from different angles.
Figure 3 test sequence diagram
First, analyze the object creation. The customer class is responsible for creating the suite and atestrunner. Note that the testrunner class contains a static function run (test), which is created by itself and then calls dorun (). This function is generally called by the customer class. The Code is as follows:
Static public void run (test suite)
{
Testrunner atestrunner = new testrunner (); // create a test driver
Atestrunner. dorun (suite, false); // run the test set with the test driver
}
The suite object is responsible for creating numerous test cases and accommodating them to itself. The customer test case inherits the testcase class, which transmits the class instead of the object to the suite object. The suite object is responsible for parsing these classes, extracting constructors, and the methods to be tested. Construct a test case in the unit of the method to be tested. The fname of the test case is the name of the method to be tested. The test result set is created by atestrunner. This seems to be in conflict with the class diagram previously described. It is suggested that a test set can contain many different test drivers. It seems that it is ideal to create a result set first. Obviously, only one method is used to process the test results, so this method is equally feasible.
Second, from the execution of the test action, the test actually starts from suite. Run (result. The Code is as follows:
Public void run (testresult result)
{
// Obtain all test cases from the case set and execute them separately
For (enumeration E = tests (); E. hasmoreelements ();)
{
If (result. shouldstop ())
Break;
Test test = (TEST) E. nextelement ();
Runtest (test, result );
}
}
Once the test case starts to be executed, a callback policy is used to hand over the result. The test driver atest runner can track and process each step of the test. This virtually creates a large monitoring system that allows you to pay different levels of attention to events at any time.
We will analyze the design patterns of the involved action behaviors:
1. template method (Template Method) class behavior pattern. Its essence is to first establish the skeleton of the method, and try to push the specific implementation of the method backward as much as possible. Testcase. runbare () adopts this mode, and the customer class can reload three of its methods to improve the scalability of the test.
Public void runbare () throws throwable
{
Setup ();
Try {runtest ();}
Finally {teardown ();}
}
2. The behavior mode of a Command object is essentially encapsulating an action as an object without caring about the receiver of the action. In this way, the receiver of the action can be determined only when the action is executed. The interface Test is a Command set, so that different Test methods of different classes can use the same interface Test to construct its framework structure. This makes testing integration much easier.
JUnit Exception throw Mechanism
The exception levels of JUnit are divided into three layers: 1. failure: The test Failure that the customer predicted can be detected by the Assert method; 2. error: An Error occurred during the test. 3. systemerror, JUnit thread death level exception, this situation rarely occurs. These three exceptions of JUnit are well reflected in the RunProtected () method of TestResult class. The Protectable interface is used to encapsulate the Test execution method. In fact, p. protect executes test. runBare ().
Public void runProtected (final Test, Protectable p)
{
Try {p. protect ();}
Catch (AssertionFailedError e)
{AddFailure (test, e );}
Catch (ThreadDeath e)
{Rethrow e ;}
Catch (Throwable e)
{AddError (test, e );}
}
The code first checks whether it is Assertion FailedError and then determines whether it is a serious ThreadDeath. This exception must be Rethrow to ensure the real death of the thread. If not, it is an accident.
The first two exceptions are stored in the test result set. After the test is completed, the exceptions are printed in sequence for your reference.
Several suggestions for JUnit implementation
From the above analysis, we can understand the structure and process of JUnit. However, when using JUnit, we also need to describe the following suggestions:
1. The customer class can reload runtest (). Its default implementation is to call the test method named fname. If you do not use testsuite to load testcase, You need to overload it. Of course, this method is not in favor of use and is not conducive to integration. In addition, the functions of setup () and teardown () seem to be the same as the constructor, but if there is a class inheritance relationship between the test cases, using constructors to initialize some parameters will cause data confusion, it is not conducive to determining the validity of the test results.
2. The call sequence of the function to be tested is uncertain. The data structure used is vector (). If order relationships are required, you can combine them and use the same test method.
3. In order to make the test results clear and clear, it is best not to print the output in the program, or the print output of the program and the JUnit test should not use the same data source system. Out. In fact, these are two testing habits. Direct Printing and output are more traditional. Considering the testing motivation, it is also more casual and the results need to be observed manually. If many outputs are printed directly, the observer may not be able to obtain satisfactory results.
In addition, how can we expand this testing framework? The JUnit. Extensions package provides several tips. We can use JUnit. Extensions. activetest to run a test instance in different threads. You can use the decorator mode to add new functions to the test case. For details, refer to JUnit. Extensions. testdecorator and its subclasses JUnit. Extensions. testsetup, JUnit. Extensions. repeatedtest. These only provide some broaden of thinking, involving specific testing objectives, and further exploration is required. |