Unit Test (Zhuang)

Source: Internet
Author: User

After several months of testing, I have a certain understanding of the test. I found that unit testing is a very important part of the test. So I am interested in the unit test and read the materials and practices. I have summarized some unit tests and hope to help you and get some valuable insights.

1. What is unit test?
Unit testing is a short piece of code written by developers. It is used to check whether a very small and clear function of the tested code is correct. Generally, a unit test is used to determine the behavior of a specific function under a specific condition (or scenario. For example, you may put a large value into an ordered list, and then confirm that the value appears at the end of the list. Alternatively, you may remove characters that match a certain pattern from the string and confirm that the string does not contain these characters.

2. Why unit testing?
When writing code, it must be debugged repeatedly to ensure that it can be compiled. If the code is not compiled, no one will be willing to deliver it to his boss. However, by compiling the code, it only shows that its syntax is correct, but it cannot guarantee that its semantics is correct. No one can easily promise that the behavior of this Code must be correct.

Fortunately, unit testing guarantees our commitment. Writing Unit Tests is used to verify whether the behavior of this Code is consistent with what we expect. With unit testing, we can confidently deliver our own code without any worries. However, we also have some misunderstandings about unit testing. What are the misunderstandings?

(1) It takes too much time to write unit tests.

The sooner bugs are detected during development, the more time they can be saved and more risks can be reduced. If errors are not modified in time, debugging and modification are difficult and time-consuming due to errors found later. Second, the more maintenance, the more messy the code structure, and even the actual thinking.

(2) It takes too long to run the test.

A proper test won't make this happen. In fact, most tests are executed very quickly, so you can run thousands of tests within a few seconds. However, sometimes some tests take a long time. In this case, you need to separate these time-consuming tests from other tests. You can run the test once a day or once a few days.

(3) testing code is not my job

The job is to ensure that the code can be completed correctly. On the contrary, testing code is indispensable.

(4) You cannot test the code because it is unclear.

If you do not know the code behavior, it is estimated that it is not the time for encoding. If you do not know the code behavior, how do you know that the code you wrote is correct?

(5) but these codes can all be compiled

Code compilation only verifies that its syntax passes, but it cannot be guaranteed that its behavior is correct.

(6) do less tests when the project progress is tight, and do more tests when the time is rich

This is a manifestation of the absence of emphasis on software testing, as well as the chaotic process management of software projects, which will inevitably reduce the quality of software testing. A reasonable project schedule is required for the smooth implementation of a software project, including a reasonable test plan, risk analysis and corresponding countermeasures for any problems in the project implementation process, do not simply shorten the test time, manpower, and resources because of the delay of development progress. The test is incomplete due to the shortening of the test time, and the potential risks caused by the decline in Project Quality often lead to greater waste. The best way to overcome this problem is to strengthen the planning and control of the software process, including the software test plan, test design, test execution, test measurement and Test Control.

(7) software testing has no prospects. Only programmers are the masters of software.

The success of a project is often determined by individual all-powerful programmers who are responsible for the overall design and detailed program design. They think that software development is code writing, and the impression is that programmers are really cool people, has a high position and treatment. Therefore, in this environment, software testing is not very important, and the status and treatment of Software testers are naturally very low, and even Software Testing becomes dispensable. As the market continues to improve the quality of software, software testing will become more and more important, and the status and treatment of corresponding software testers will gradually increase. In large companies with relatively standardized software processes, such as Microsoft, the number and treatment of Software testers are not much different from those of programmers, and the treatment of excellent testers is even higher than that of programmers. Software testing will become an industry with great development prospects. Software Testing has a promising future. The market needs more testers with rich testing technology and management experience. They are also software experts.

3. What are the advantages of unit testing?
(1) It is a verification behavior.

Every function in the program is tested to verify its correctness. It provides a delay for future development. Even after development, we can easily add features or change the program structure without worrying about the damage to important things in this process. It also guarantees code refactoring. In this way, we can improve the program more freely.

(2) It is a design behavior.

Writing Unit Tests will let us observe and think from callers. In particular, writing test-first forces us to design programs that are easy to call and testable, which forces us to lift coupling in software.

(3) It is a document writing activity.

Unit testing is an invaluable document that best shows how functions or classes are used. This document can be compiled, run, and kept up-to-date, always synchronized with the code.

(4) It is regression.

Automated unit tests avoid code regression. After compilation, you can run tests anytime, anywhere.

 

4. When to perform Unit Testing

The sooner the unit test is, the better. How early is it? XP Development Theory focuses on TDD, that is, test-driven development. First, write the test code before development. In actual work, it is important to be efficient and comfortable without overemphasizing what comes first. From the perspective of experience, first write the product function framework, then write test functions, write test cases for the functions of the product function, then write the code of the product function, and run the test every time a function is written, test cases can be supplemented at any time. The framework for writing product functions first refers to the implementation of function null. If there is a return value, a value is returned. After compilation is passed, the test code is written, the function name, parameter table, and return type should all be determined. The tested code written in later may be less likely to be modified.

 

5. Who will perform the unit test?

Unit Testing is different from other tests. unit testing can be considered as part of coding and should be completed by programmers. That is to say, the code that passes the unit test is the completed code, you must also submit the test code when submitting the product code. The test department can perform a certain degree of review.

 

6. unit test tasks

Unit test tasks include:

 

(1) Module Interface Test

Module Interface testing is the basis of unit testing. Other tests make sense only when the data can be correctly imported into or exported from the module. The following factors should be taken into account when the test interface is correct:

Whether the number of input parameters is the same as that of formal parameters;
Whether the input parameters match the formal parameters;
Whether the dimensions of the input parameters are consistent with those of the formal parameters;
Whether the number of actual parameters provided when other modules are called is the same as that of the called module;
Whether the attribute of the actual parameter given when other modules are called matches the parameter attribute of the called module;
Whether the dimensions of the actual parameters provided when other modules are called are consistent with those of the called module;
Whether the number, attributes, and order of parameters used to call a predefined function are correct;
Whether parameter reference irrelevant to the current entry point exists;
Whether read-only parameters have been modified;
Whether the full-process variables are consistent in each module;
Whether to pass certain constraints as parameters.

If the module contains external input and output, consider the following factors:
Whether the file attributes are correct;
Whether the open/close statement is correct;
The format description matches the input and output statements;
Whether the buffer size matches the record length;
Whether the file has been opened before use;
Whether the end of the file is processed;
Whether the input/output errors have been processed;
Whether there is a textual error in the output information

 

(2) Test the local data structure of the module;

Check the local data structure to ensure that the data temporarily stored in the module is complete and correct during program execution. Local data structures are often the root cause of errors. You should carefully design test cases and try to find the following types of errors:

Description of unsuitable or incompatible types;
No initial value for the variable;
Variable initialization or missing values are incorrect;
Incorrect variable name (spelled incorrectly or incorrectly truncated );
Overflow, overflow, and address exceptions occur.
In addition to the local data structure, if possible, the impact of global data on the module should also be checked during unit testing.

 

(3) module boundary condition test;

Boundary Condition testing is the final and most important task in unit testing. The software often fails on the boundary. The boundary value analysis technology is used to design test cases for the boundary value and its left and right, and it is likely to discover new errors.

 

(4) All independent path tests in the module;

Each independent execution path should be tested in the module. The basic task of unit test is to ensure that each statement in the module is executed at least once. In this case, the test case is designed to discover errors caused by incorrect calculation, incorrect comparison, and inappropriate control flow. In this case, basic path testing and cyclic testing are the most common and effective testing techniques. Common Errors in computing include:

Misunderstanding or incorrect operator priority;
Hybrid Operation;
The initial value of the variable is incorrect;
Insufficient precision;
The expression symbol is incorrect.

Comparison and judgment are often closely related to the control flow. Test cases should also focus on the following errors:

Compare objects of different data types;
The logical operator or priority is incorrectly used;
Due to the limitations indicated by the computer, we expect the two numbers that are theoretically equal but not actually equal;
An error occurred while comparing operations or variables;
Cyclic termination conditions may not exist;
Iteration divergence cannot exit;
The loop variable is incorrectly modified.

(5) test each error handling path of the module.

A good design should anticipate various error conditions and preset various error handling paths. The error handling paths also need to be carefully tested. The test should focus on the following problems:
The output error information is hard to understand;
The recorded errors do not match the actual errors;
The system has been involved before the custom error handling segment of the program runs;
Improper exception handling;
The error statement does not provide sufficient error identification information.

7. unit test cases and Case Design
After learning about the unit test task, we will introduce the test cases below. The test cases are also the core of unit test and decide whether your unit test is successful. The core of a test case is input data. The expected output is determined based on the input data and program functions. That is to say, if the input data of a program is determined, the expected output can be determined, all test cases are similar in generating/destroying tested objects and running test statements.

 

Unit test cases are generally designed using the logical coverage method and the basic path method.

(1). logic coverage Method
Logic coverage is a test case design technology based on the internal logic structure of the program. This method requires the tester to have a clear understanding of the logical structure of the program. Logical coverage can be divided into statement coverage, decision coverage, condition coverage, Decision-condition coverage, condition combination coverage, and path coverage.

Statement overwrite is to design several test cases to run the tested program so that each executable statement can be executed at least once.

Decision coverage is to design several test cases and run the tested program so that each of the true branches and false branches in the program can go through at least once.

Conditional coverage is to design several test cases and run the tested program so that the values of each criterion in the program can be executed at least once.

Decision-condition coverage is to design enough test cases so that all possible values of each condition in the judgment are executed at least once, and all possible judgment results of each judgment are also executed at least once.

Conditional combination coverage is to design enough test cases to run the tested program so that all possible combinations of conditional values can be executed at least once.

Path testing is to design enough test cases to cover all possible paths in the program.

(2) Basic Path Method
The basic path test method is based on the control flow diagram of the program. By analyzing the loop complexity of the control structure, the basic executable path set is exported to design the test case method. The designed test case should ensure that each executable statement of the program in the test should be executed at least once. The basic path test includes the following five aspects:

Control Flow Diagram of a program: A graphical method that describes the control flow of a program.

Complexity of the program environment: McCabe complexity measurement; from the loop complexity of the program, you can export the number of independent paths in the basic path set of the program, this is the upper limit of the number of test cases required for each executable statement in the program to be executed at least sequentially.

Export test cases.

Prepare test cases to ensure the execution of each path in the basic path set.

Graphical matrix: a software tool that assists in basic path testing. It can be used to automatically determine a basic path set.

 

(3) unit test case design cases
I have read a very good unit test case design case a long time ago, but it is a pity that it is not retained. A good unit test case is very important for getting started with unit test. I hope this case can help you understand unit test and the importance of unit test.

For example, if you want to perform a unit test on the currency conversion unit function. How should I perform a unit test on a function? The first consideration is the input and output parameters of the conversion unit function in this currency, and the second is whether the output result is equal to the expected value. The unit test processing class is created again, and a test method to test the function is established accordingly, generally, test *** () is used according to JUnit specifications ****().

Start to prepare the unit test class and test method. The input parameters of the currency conversion function are: target currency, conversion currency, amount, and the output is the amount of the target currency after conversion. Establish the first simple unit test processing class and Unit Test method:

Public bigdecimal testcurrychange (){

Reference the currency conversion function and enter the test parameters. If the test parameter is: The target currency is RMB, the conversion currency is USD, and the amount is 100.00.

Bigdecimal bgresult = 799.95;

If (bdresult. Equals (function ("10", "32", 100.00) = false ){

Throw new exception ("Conversion error !");

}

}

The first unit test function has been written and can be used for unit testing. However, it cannot be used to fully test whether the currency conversion function is completely correct. The conversion structure of the first amount may be different. The conversion between the second and different currencies may be different, different results. What should we do next?

You can use this method to create multiple functions as above, but the input parameters are different, for example, the amount is different; the target currency is different from the conversion currency. In this way, you can check whether the currency conversion function is correct in different directions. In general, in this case, the amount input parameter is processed only by sending a boundary, taking the minimum and maximum values as the input parameters for testing. In addition, depending on the actual situation, the number of medium currencies to be converted, perform the exhaustive method, process all currencies, and test the currency combination based on the amount. I will not write the code here.

However, the above method is a feasible method, but it is complicated to handle. If there are many currency conversions, a lot of unit test methods need to be written in combination, which is cumbersome to use, what should I do? In this case, you can use the array method + the loop method to implement it, so that it is easy to avoid the hassle of the above method. The specific implementation is not listed. You can study it on your own.

Writing Unit Tests is also a very interesting thing. The above methods may be implemented in different situations. Not every unit test case must be the most perfect, so that the requirements and objectives can be met. There are still a lot of methods to write test cases. You can use the best method based on the actual situation.

 

 

8. Introduction to unit test tools
Unit testing tools vary with development languages. Java language development system: currently, JUnit is popular ;. net Language Development System: nunit; C/C ++ language development system: cppunit is currently popular. Currently, the system is developed using Java. Therefore, many studies on JUnit have been made, so we have the opportunity to discuss with you. If you are interested in other products, you can also study them on your own. There are also many unit test tools that you can choose based on your specific situation.

JUnit introduction:

Http://blog.csdn.net/askmyself/archive/2005/10/10/498599.aspx

Nunit introduction:

Http://blog.csdn.net/litp/archive/2005/11/11/527684.aspx

Http://blog.csdn.net/litp/archive/2005/11/11/527684.aspx

 

Cppunit introduction:

Http://blog.csdn.net/lzw2005/archive/2005/09/23/488013.aspx

Http://blog.csdn.net/casualgame/archive/2005/03/27/332162.aspx

  

Through reading and understanding of unit testing, I hope to introduce the unit testing tool JUnit into the current system development. In practice, it is not very feasible, A database connection cannot be obtained well in the parameters for testing. Therefore, you can use other methods to replace JUnit for unit testing. writing one or more unit testing business processing classes and log4j (logging) can also implement unit testing, this is relatively troublesome. You need to write the creation and release of the object and test the business processing. In actual situations, we may also encounter such problems. We hope that you can find your own appropriate methods in practice, rather than using unit testing tools.

 

 

9. Summary
All in all, unit testing makes our development work easier and gives us more confidence in our code. Whether it is a large project or a small project, whether it is a time-tight project or a project with ample time, as long as the code is not written once and never changed, it is worth the money to write unit tests, it has become an indispensable part of our coding.

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/giftbook/archive/2005/12/26/562609.aspx

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.