Chapter 1. Software Test
Junit is an open source java testing framework buy to write and rain refeatable tests
1.1. Test classification
2 White box test - treat the test object as an open box, the logical structure and other information inside the program are open to the tester.
2 Regression Test - Software or Environment Repair or "Re-Test", automatic test tool is especially useful to this type of test.
2 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.
1.2. Unit test overview
1.2.1. Benefits of unit test
1) Improve the development speed - Test is performed in an automated manner, enhance the performance efficiency of the test code.
2) Improve software code quality - it uses a small version to publish to integration, which is easy to implement the person's decentralization. At the same time, the reconstruction concept is introduced, so that the code is cleaner and elastic.
3) Improve system trustedness - it is a regression test. Support repair or correction "re-test" to ensure the correctness of the code.
1.2.2. Aiming of the unit test
2 Software development for the process for the process.
2 Object-oriented software development for objects.
2 You can do class test, function test, interface test (most commonly used in test classes).
1.2.3. Unit test tool 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 test framework comes from SMALLTalk's SunIt, and the most outstanding application is an open source of Open source by Erich Gamma ("Design Mode" and the founder of Kent Beck (XP (Extreme Programming).
Chapter 2. JUnit Getting Started
2.1. Advantages of JUnit
2 can separate the test code to the product code;
2 The test code for a certain class can be applied to another class with less changes;
2 Easy to integrate into the construction process of testers, JUnit and Ant combination can implement incremental development;
2 JUnit is a public code, it can be carried out secondary development;
2 can be easily expanded for JUnit;
2.2. JUnit unit test writing principle
2.2.1. "First write test, write code"
2 From technology to force you to consider a class function, that is, this class provides an external interface, not too early to fall into its details. This is a design principle that is advocated.
2 Good test is actually a good document. This type of user can often understand its functionality by viewing the test code of this class. Special, if you get a program of others, write testing is the best way to understand the functionality of this program. The principle of XP is Make IT Simple, not recommended to write another document, because the project is often changed during the development process, if the document is written in the early stage, there is a synchronization document after the code changes, more work, and due to project time The incomplete or inconsistent with the document is inconsistent with the code, and it is better not to write. And if you write a document after the project, developers often have forgotten all kinds of considerations when writing code, and there is a pressure of the next project, and managers are not willing to write documents for the old project. Problems leading to future maintenance. 2 No one can guarantee that the demand is not changed, and the past projects often have a big headache to the changes in demand, and this change will bring other places. To this end, in addition to the design of the design to split items (loosely coupled), but if there is a test, a good test framework has been established, and the change is modified, if the code is modified, just re-run the test code, if The test passed, but also guaranteed the success of the modification. If there is an error in the test, it will immediately find that the wrong is wrong. Modify the appropriate part and run the test until the test is fully passed.
2.2.2. Objective test replicable test = Simple test Programme
Objective and Replicable are the most concerned about the Unit Testing.
Objective means that every TestCase should be a purpose, not a cloud of the cloud, "Every class should be unit Testing"; Replicable means that TestCase should be reusable. As a UNIT TESTING Framework, JUnit is very good to respect these two principles. It is largely used to write TestCase people to control the Objective feature, and the replicable method and API have also largely improved the developer's writing. The efficiency of TestCase. As long as the developer truly realizes the necessity of Unit Testing, he will definitely like the benefits of JUnit, not simple to learn and use. To know that Junit is able to truly improve development efficiency and code quality.
2.2.3. General principles
2 is the preparation of the simplified test, which includes the study of the test framework and the preparation of the actual test unit.
2 is to keep the test unit persistence.
2 is the use of existing tests to write related tests.
2.3. Characteristics of JUnit
2 Use the assertion method to determine the expected value and the actual value difference, return the boolean value;
2 Test the drive device uses a common initialization variable or instance;
2 Test package structure facilitates organization and integration operation;
2 support graphical interaction mode and text interaction mode;
2.4. JUnit frame composition
The JUnit framework is a typical composite mode.
TestSuite can accommodate objects from TEST; when the Run () method of the TestSuite object is, it is traversed the object that is accommodated, and the RUN () method is called one by one.
1) TestCase, the method of testing the test goal and the process, which can be called test case
2) The collection of TestSuite test cases can accommodate multiple test cases, referred to as test packages
3) Description and record of TestResult test results
4) Event Loker 5 in the TestListener Test Process During TestFail, each test method is described in the description of the expected inconsistency, called its test failure element
6) An error abnormality in AssertionFaileDerror Junit Framework
2.5. Interfaces and classes used in Junit
2.5.1. 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.
2.5.2. TestCase Abstract Class - Defining Test Method
2.5.2.1. Definition
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.
2.5.2.2. Precautions
2 The independence of the test: Only one subject is tested once, it is convenient to locate an error position. This is 2 layers: a TestCase, only test an object; a TestMethod, only testing a method in this object;
2 give a suitable name for the test method;
2 For the cause of failure in the Assert function, such as: Asserttrue ("... Should Be true", ...), easy to find out. In this example, if it is not possible to pass Asserttrue, then the given message will be displayed. Each Assert function in JUnit has the first parameter is a function prototype of the message when an error is displayed;
2 Test all places that may cause fail, such as: Frequent changes in a class. For classes that only contain Getter / Setter, if it is generated by IDE (such as Eclipse), you can do not test; if it is manual writing, then it is best to test it;
2 The code in Setup and Teardown should not be related to test methods, but should be globally related. For example, the code in the SETUP and TEARDOWN should be the code required by A and B;
2 Test code organization: the same package, different directories. In this way, the test code can access the protected variable / method of the test class, which is convenient for test code. Putting in different directories, it is convenient for the management of test code and the packaging and release of code; SRC <= source code root
| --- COM
| --- MOD1
| --- Class1
JUnit <= test code root directory
| --- COM
| --- MOD1
| --- Class1
2.5.3. 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.
2.5.4. TestSuite test package - a combination of multiple tests
2.5.4.1. Definition
The TestSuite class is responsible for assembling multiple Test Cases. The class to be tested may include multiple tests of the test, and TestSuit is responsible for collecting these tests, allowing us to complete all of the tests that are tested in one test, regardless of whether the test is in the same File.
The TestSuite class implements the TEST interface and can contain other Testsuites. It can handle all thrown exceptions when adding TEST.
Listing A shows our test package contains two tests:
Listing A: Test Suite
Public static test suite () {
Testsuite suite = new testsuite ();
Suite.Addtest (New XMLTest ("TestPersoncount"));
Suite.Addtest (New Xmltest ("TestContainSperson");
Return suite;
}
2.5.4.2. Statute
TestSuite handles test cases have 6 stations (otherwise it will be rejected)
1) Test case must be a public class (public)
2) Test case must inherit and testcase class
3) Test methods for test cases must be public (public)
4) Test method of test case must be declared as Void
5) Pre-test method of test method in test case must be test6) test cases in test methods misunderstand parameters
2.5.4.3. How to use the test package to perform a test?
Perform testing needs to create an executable class to call the JUnit test runner. Runner is responsible for performing test packages, running all tests and outputs test results.
List B shows how to integrate the test package into the test runner:
Listing B: XmlteStrunner.java
Import junit.framework.test;
Import junit.framework.testsuite;
Import Xmltest;
Public class xmlteestrunner {
// public static test suite () {
// TestSuite Suite = new testsuite ();
// suite.addtest (New XMLTest ("TestPersonCount");
// suite.addtest (New Xmltest ("TestContainSperson");
// Return Suite;
//}
/ **
* Show how to pass the name of the class to the test package constructor from moving loading test.
* /
Public static test suite () {
Return New TestSuite (XMLTest.class);
}
Public static void main (String [] args) {
Junit.textui.teStrunner.run (Suite ());
}
}
2.5.4.4. How to create a test package?
Manual creation and automatic creation
2.5.5. TestResult result Class and Other Categories 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 an exception
The TestListener Interface is an event monitoring, which is available for Testrunner class. It informs the object-related events of Listener, including testing start StartTest (Test Test), test ended Endtest (Test Test), error, increasing exception Adderror (Test Test, Throwable T) and increasing failed AddFail (Test Test, AssertionFailerror T)
TestFailure failure class is a "failure" collection class that explains the abnormal situation that occurs during each test execution. Its TSTRING () method returns a brief description of the "failure" situation
2.6. Team development model under java
1) Mode of using CVS (version control) Ant (Project Management) JUnit (integrated test):
2) Go to work every morning, each developer gets a copy of the entire project from CVS Server.
3) Get your own task, first write the test code for today's task.
4) Write the code of today's task, run the test until the test passes, the task is completed
5) One or two hours before get off work, each developer submitted the task to CVS Server
6) Then run automatic testing through the supervisor, which test is wrong, and find the relevant personnel to modify until all tests are passed. Get off work ...
2.7. Basic steps for writing test classes
The general step of writing test code using JUnit is:
2) Introduce the JUnit frame package. Import junit.framework. *. 3) Define the test class name, which is generally attached to Test after the class name to be tested.
4) Test class inherit the TestCase class of JUnit.
5) Implementing the construction method of the class, you can simply call Super (Name) in the construction method.
6) Implement the main () method of the class, simply call junit.textui.teStrunner.run (SimpleTest.class) in the main () method to specify the execution test class.
7) Overload the setup () and teardown () method, the setup () method is used to perform an initialization operation of the environment when performing each test case (such as an open database connection), and the Teardown () method is used to perform each test case after cleaning Environment (such as turning off database connection).
8) Write each test case and write some TestXxxxx () method (Test before the method to test).
2.8. Integration with ANT?
2.9. Generate HTML report
Chapter 3. JUnit extension
3.1. HttpUnit
HttpUnit is defined a WebConversion, then analog Browser's actions and results for Web-forms, the same HTTPUnit, which can also simulate tests in the container, such as servlet.
I personally think httpunit has fundamentally solved the Web-form test problem, which can be said to be more original tests, simulate the entire interaction process through the form of Request and Response, and also provide testing for LINK, it should be easier Let users really understand its advantage. Instead, Cactus must pass a large round of configuration before testing, and more troublesome is that it is difficult to simulate a complete process with CACTUS, and only can continue to test each servlet method Method through multiple Test Method, and then prove these There is no problem with Methods, it is difficult to indicate that these Methods are string after they come.
3.2. CACTUS
CACTUS is a JUnit extension in the container, which extends TestCase to three forms of JSP, Sevlet, and Filter, then define a test process through some special methods, such as Beginxxx, etc.) to simulate a series of interactive containers. test
Chapter 4. Java Language Test Course
training content
1, JUnit essence;
2, test strategy;
3, test components.
Course Outline
4.1. Part 1: JUnit essence
1 JUnit Introduction
1.1 installation
1.2 a simple example
1.3 understanding unit test framework
1.4 Setup JUnit
1.5 use JUnit test
1.6 summary
2 explore JUnit
2. Explore the JUnit core
2.2 Start test with Test Runners
2.3 Composition with TestSuite
2.4 Connection parameters with TestResult
2.5 Pay attention to test results with TestListener
2.6 Effect of test
2.7 gradually advancement through TestCalculator
2.8 Summary
3 Sampling JUnit
3.1 Introducing Controller Components
3.2 Let's test it!
3.3 Test abnormal processing
3.4 Establish a project for testing
3.5 Summary
4 check software test
4.1 Demand for Unit Test
4.2 Different kinds of tests
4.3 Decide the level of testing
4.4 Test Drive Development
4.5 Test in the development cycle
4.6 Summary
5 Automatic JUnit
5.1 Day in life
5.2 running test from Ant
5.3 running test from Maven
5.4 running test from eclipse
5.5 Summary
4.2. Part II: Test strategy
6 Coarse test with pile
6.1 Introduction Pile
6.2 Examples practice an HTTP connection
6.3 Pile of resources for web servers
6.4 Piling
6.5 Summary
7 Use the Mock object to isolate the test 7.1 Introduction Mock object
7.2 MOCK Tasting: A simple example
7.3 Using the MOCK object as a reconstruction technology
7.4 Production an example of HTTP Connection
7.5 Using Mock as Trojan Horse
7.6 Decide when using Mock objects
7.7 Summary
8 Test in the container 8 with CACTUS
8.1 Unit test components
8.2 Test components using the MOCK object
8.3 What is an integrated unit test?
8.4 Introduction CACTUS
8.5 Using the CACTUS Test Component
How to work 8.6 CACTU?
8.7 Summary
4.3. Part III: Test Components
9 Connecting Servlet and Filter
9.1 Presenting Management Application
9.2 Write a servlet test with CACTUS
9.3 Test servlet using the Mock object
9.4 Write a Filter test using CACTUS
9.5 When is CACTUS, when is the Mock object
9.6 Summary
10 unit tests for JSP and Taglib
10.1 re-registration management
10.2 What is the JSP unit test?
10.3 Test a JSP using CACTUS isolation unit
10.4 Test taglib using the CACTUS unit
10.5 Test taglib using the MOCK Object Unit
10.6 When does it use CACTUS, when is the Mock object
10.7 Summary
11 Communicate to the database application
11.1 Introduction Unit Test Database
11.2 Test business logic from the database
11.3 Test the continuous code from the database
11.4 Write Database Integration Unit Test
11.5 Run CACTUS test using Ant
11.6 Adjustment of Building Performance
11.7 Comprehensive database unit test strategy
11.8 Summary
12 EJB for unit testing
12.1 Defining an example EJB application
12.2 Using a positive strategy
12.3 Test JNDI code using the MOCK Object Unit
12.4 Unit Test Session Beans
12.5 Using the Mock object to test the message-driven Beans
12.6 Test entity Beans using Mock objects
12.7 Select the correct MOCK object policy
12.8 Testing the integrated unit
12.9 Using JUnit and Remote Call
12.10 Using CACTUS
12.11 summary