Team blog: Software Unit Testing Overview

Source: Internet
Author: User
Tags xunit

1. Several related concepts

White Box testing-the test object is treated as an open box, the logic structure inside the program and other information is public to the tester.

Regression testing-The automated testing tool is especially useful for tests such as software or environmental remediation or corrections.

Unit Test--is the least granular test to test a feature or block of code. It is usually done by a programmer because it needs to know the details of internal programming and coding.

junit--is a Java test framework that develops source code for writing and running repeatable tests. He is an example for the xunit of the Unit Test framework system (for the Java language). Mainly used for white box testing, regression testing.

2. Unit Test Overview

2.1. Benefits of Unit Testing

A, improve the speed of development-testing is performed in an automated manner, improving the execution efficiency of the test code.

B, improve the quality of software code-it uses a small version released to the integration, easy to implement personnel debugging. The refactoring concept is also introduced to make the code cleaner and more resilient.

C, to improve the reliability of the system-it is a regression test. Support for "re-testing" after repair or correction ensures that the code is correct.

2.2. Object for unit Testing

A, process-oriented software development for the process.

B, object-oriented software development for the object.

C, can do class testing, functional testing, interface testing (most commonly used in the test class method).

2.3. Unit testing tools and frameworks

Currently the most popular unit testing tool is the Xunit Series framework, commonly used according to the language is divided into JUnit (Java), CppUnit (C), Dunit (Delphi), NUnit (. net), PhpUnit (PHP) and so on. The first and most prominent application of the test framework was the open source JUnit provided by Erich Gamma (author of design mode) and Kent Beck (Extreme programming).

About 3.Junit Getting Started

3.1. JUnit Benefits and JUnit Unit Test authoring Principles

Benefits:

A, you can separate the test code from the product code.

B, the test code for one class can be applied to another class's test with fewer changes.

C, easy integration into the tester's build process, the combination of junit and ant can implement incremental development.

D, JUnit is open source code, can be developed two times.

C, it is easy to extend JUnit.

Writing principles:

A, is to simplify the writing of tests, this simplification includes the test framework of learning and the actual test unit of the writing.

B, is to keep the test unit persistent.

C, it is possible to use the existing tests to write related tests.

3.2. Features of JUnit

A. Use the assertion method to determine the difference between expected and actual values, and return a Boolean value.

B, test-driven devices use common initialization variables or instances.

C, test package structure for easy organization and integration operation.

D, support diagram interactive mode and text interaction mode.

3.3. JUnit Framework Composition

A. A set of methods and procedures for testing test targets, which can be called Test Cases (TestCase).

B, a collection of test cases that can hold multiple test cases (TestCase), which is called a test package (TestSuite).

C, description and record of test results. (TestResult).

D, the event listener during the test (Testlistener).

E. A description of the expected inconsistency between each test method and its test failure element (Testfailure)

F, error exception (Assertionfailederror) in the JUnit framework.

The JUnit framework is a typical composite pattern: Testsuite can accommodate any object derived from test, and when the run () method of the Testsuite object is called, it iterates through the objects it holds and calls their run () methods one by one. (Refer to "programmer" 2003-6).

3.4. JUnit Installation and Configuration

JUnit Installation Steps Decomposition:

Download the JUnit package in http://download.sourceforge.net/junit/and unzip the JUnit package into a physical directory (for example, C:\Junit3.8.1).

Record the directory name where the Junit.jar file is located (for example, C:\Junit3.8.1Junit.jar).

Enter the operating system (whichever is the Windows2000 operating system) and click "Start Settings Control Panel" in the order.

Select System in the Control Panel options, click Environment Variables, select the Class-path keyword in the variables list box in system variables (case insensitive), and add if the keyword does not exist.

Double-click the "class-path" keyword to add the string "C:\Junit3.8.1Junti.jar" (note that if there is already another string, add a semicolon ";" to the end of the character string) so that the modified JUnit can be applied in the integrated environment.

For the IDE environment, add a different set of Ides to the Lib for the JUnit items that need to be used.

3.5. Common interfaces and classes in JUnit

Test interface--run tests and collect test results

The test interface uses the composite design pattern, which is a common interface for individual test cases (TestCase), aggregation test patterns (TestSuite), and test Extensions (Testdecorator).

its public int counttestcases () method, which counts how many testcase this test has, and the other is public void run (TestResult), TestResult is the instance that accepts the test results, Run method to perform this test.

TestCase abstract class--defining a fixed method in a test

TestCase is an abstract implementation of the Test interface (cannot be instantiated and can only be inherited) its constructor testcase (string name) creates a test instance based on the name of the test entered. Since each testcase must have a name at the time of creation, if a test fails, it will identify which test failed.

The setup (), TearDown () method contained in the TestCase class. The Setup () method sets all the variables and instances required for the test to be initialized, and executes the setup () method again before each test method in the test class is called in turn. The TearDown () method releases the variables and instances referenced in the test program method after each test method.

When developers write test cases, they simply inherit testcase to complete the Run method, and JUnit obtains the test case, executes its run method, and records the test results in TestResult.

Assert static Class--a collection of a series of assertion methods

The assert contains a set of static test methods used to correct the expected and actual values, i.e. the test fails, the Assert class throws a Assertionfailederror exception, and the JUnit test framework failes and records the error. At the same time the flag is failed to pass the test. If a string is specified in the class method, the parameter will be used as the identification information for the assertionfailederror exception, telling the tester to change the exception details.

JUnit provides 6 categories of 31 groups of assertion methods, including underlying assertions, numeric assertions, character assertions, Boolean assertions, and object assertions.

where Assertequals (Object expcted,object Actual) internal logic is judged using the Equals () method, which indicates that it is better to use this method to compare the values of the corresponding class instance when asserting that the internal hash value of two instances is equal. The Assertsame (Object expected,object Actual) internal logic judgment uses the java operator "= =", which indicates that the assertion determines whether two instances are from the same reference (Reference), It is best to use this method to compare the values of instances of different classes. Asserequals (string message,string expected,string Actual) This method makes a logical comparison of two strings, and if not, shows where two strings differ. The Comparisonfailure class provides a comparison of two strings, and a mismatch gives a detailed difference character.

Testsuite Test Package Class-a combination of multiple tests

The Testsuite class is responsible for assembling multiple test Cases. The class to be tested may include multiple tests on the class being tested, and testsuit is responsible for collecting these tests so that we can complete multiple tests of the tested class in one test.

The Testsuite class implements the test interface and can contain other testsuites. It can handle all thrown exceptions when the test is added.

Testsuite processing test case has 6 protocols (otherwise it will be refused to perform the test)

A test case must be public

B test cases must inherit from the TestCase class

Test methods for C test cases must be public

The test method for the D test case must be declared void

The pre-noun of the test method in the E test case must be test

F test cases in which the test method mistakenly passes any parameters

n TestResult result classes and other classes and interfaces

The TestResult result class aggregates the results of any test accumulation and passes each test's run () method through the TestResult instance. TestResult is executing testcase if the failure throws an exception

The Testlistener interface is an event monitoring protocol that can be used by the Testrunner class. It informs listener about the object-related events, including the test start starttest (test test), the end of the testing endtest, the error, adding an exception adderror (Test test,throwable t) and increase failure addfailure (Test test,assertionfailederror t)

The Testfailure failure class is a collection class for a "failed" condition that explains the exceptions that occur during each test execution. Its ToString () method returns a brief description of the "failed" condition

3.6. One instance of JUnit

The simple example in the console is as follows:

1. Write a triangle class to be tested and create a subclass of TestCase Exampletest:

2. Write one or more test methods in Exampletest, asserting the desired result (note: test as the beginning of the method to be tested so that these methods can be automatically found and tested)

3. Write a Suite () method in Exampletest, which uses reflection to dynamically create a test suite that contains all the testxxxx methods:

There is nothing special about the operation of JUnit itself. There are 6 types of test items available, one for different test subjects or a target.

Test case: This is the most common, that is, the program code in the class testing.

Test suite: At this higher level, you can test more than one class at a time. The effect is the same as performing multiple testcase separately.

JDBC Fixture: This is a test for database linking. (seldom used, not quite understood.) I learned the default JDBC database.

Jndi Fixture: This is equivalent to a container test. If the main content is to test those who store links fixture.

In programming, often put some common links in a similar to the inside of a container, so that if the call repeatedly call the link, you can call the same container address, and then point to the inside of the link. Whether this is a kind of management.

Comparision Fixture: This is also less use of dongdong.

Custom Fixture: This is a customized setting. Just create a frame.

Junitx.framework Package Main function

The package extends the functionality of the Junit.framework.Assert in the same way as the class method.

At this point, you can use the related functions of assertions without inheriting the corresponding classes. In fact, the metadata-based testing framework basically implements assertions in this way.

Junitx.framework.Assert

Junitx.framework.ArrayAssert

Junitx.framework.ComparableAssert

Junitx.framework.FileAssert

Junitx.framework.ListAssert

Junitx.framework.ObjectAssert

Junitx.framework.NamingAssert

Junitx.framework.OrderedTestSuite

Junitx.framework.StringAssert

Junitx.framework.ThrowableAssert

2. Testing the private properties of a class

2.1 Implementation of the private properties of the test class

Use the method class of the related Class (Junitx.util.PrivateAccessor) to access private properties and methods.

Reference:

Under the Examplejunit_addons_exampleexample1 directory

Example1. Testaccount class

Example1. Account Class

2.2 How to implement the properties and methods of the Access class

Implemented using the reflection mechanism of java.

L. Using the Java.lang.Class method, get the field for the specified object, and then call

Field.setaccessible (TRUE); bypasses access check, then can access the value of field, of course

You can also set the value of field.

2. Use the relevant method of Java.lang.Class to obtain the methods of the relevant specified object, and then call

Field.setaccessible (TRUE); bypasses access checks; and finally executes the method.

3. junitx.extensions Package Main function

This package actually creates the test case tool class using the template method pattern.

The template method pattern is used, the abstract class is defined, the relevant test method is given the concrete implementation, and the creation of the test object is put into the basic method.

Examples of junit-addons frameworks are:

Junitx.extensions.ComparabilityTestCase

Junitx.extensions.EqualsHashCodeTestCase

Junitx.extensions.SerializabilityTestCase

These classes define several abstract methods, mainly those used to create objects, which need to be implemented within a specific class. In Testsuite, the addition of test cases is accomplished by using a parameterless constructor of the class, so the above classes, in order to implement the injection of the test object, adopt the method of set injection rather than the constructor injection method.

Team blog: Software Unit Testing Overview

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.