Unit test training series: (1) unit test concepts and necessity

Source: Internet
Author: User
When talking about unit testing, most people should know or have heard of it. Maybe many people think that they have also written it, and even think unit testing is very simple. What kind of training is there? In fact, this is really not as simple as you think! I can say responsibly, if you haven't studied unit tests in depth and don't know what the mock object is, maybe the unit test you have written before is not a unit test at all.

 

What is unit test?

In fact, it is not easy to say a word or two clearly. I will first borrow the definition of Baidu Encyclopedia:

Unit testing is required during software development.MinimumIn the unit test activity, the independent unit of the software willProgramOther partsIsolatedTest.

From the above definition, we can see that two words are extracted to two very critical words:Minimum Granularity,Isolation

  • Unit testing is the smallest unit of testing. It must be trustworthy and can be executed repeatedly.
  • If the scope of the test is easily extended to other classes or other similar methods, it is no longer the smallest unit, it is not a unit test!

    For example:
    The method callmethod in Class A calls the method domethod in Class B. If the domethod in Class B is not isolated during testing, this causes the unit to test the callmethod method, if the domethod method is actually implemented, this test method cannot be regarded as a unit test. (How to isolate it will be explained later)

What is the purpose of unit testing?

Someone once gave me a very simpleCodeFragment: a method that only calls several other methods, and even does not return any values. Then, ask me if this code write unit test has any value ?! It is a waste of physical strength !!

 

Public   Class Classa
{
Public   Void Callmethod ()
{
Dosomethingforyou ();
Dosomethingforthem ();
Dosomethingforme ();
}
}

In fact, there are two main reasons for this question: failing to understand the purpose of unit testing and the testability of this Code is not high. (Testability and how to improve it will be described in later sections)

Objective of Unit TestingIs used to ensure the logic of the programAs expectedIs not used to verify whether it meets the customer's needs! Establish a solid guarantee through unit testing to prevent code from being damaged in future modifications.

Are you disappointed? Unit tests are not used to verify whether the Code meets the requirements.
In fact, unit testing is a type of white-box testing that requires developers to complete. It is best to compile unit test code by WHO develops the code, the author of the Code is most familiar with the purpose of this section of code, and then compiles the unit test code to verify whether the purpose is achieved.
Unit tests cannot be used to replace other testing methods. However, in practice, unit tests can effectively help developers check code and discover potential bugs. However, this is only an extra benefit. If we do not adopt the test-first development method like TDD, thenThe fundamental purpose of unit testing is not to test whether the current Code has bugs.!

 

As mentioned above, unit tests should be written by developers themselves to verify that the Code meets the expected requirements of developers. There may be a question here. Since the developer knows exactly what the result is and runs the code once directly, it can be easily verified through breakpoint debugging? By writing code, or even more code than developing the function itself, isn't it a silly and tiring way to verify whether the method meets the purpose of writing?

 

It may be better explained through a practical scenario that we often encounter:

At the beginning of a project, the project manager splits the requirements into several modules and distributes them to different developers. In this way, everyone may be familiar with their own part of the code. After a certain stage of the project is developed and launched, some developers may leave the project and enter another new project, leaving some others for maintenance; or a large number of new developers in the next stage of the project are not familiar with the current project; of course, the most common thing is that in the bug modification stage, they are unable to arrange to modify any bugs generated completely.
At this time, there will be a common situation: because you are not familiar with the various purposes to be met by the current Code, the original correct functions are also affected when you modify a module or bug! Even worse, no one knows that this bug has appeared, and the tester needs to discover it again.

As a result, the project manager will find that the robustness of the current Code cannot be known every time the Code is modified, whether it is refactoring, new feature modification, or bug modification, are the previously written items still correct and usable?

However, if a unit test is written in this project at the beginning, we can run all the unit tests through a convenient automated unit test framework, then, check whether all codes covered by the unit test before this modification are still running normally (in line with the previous unit test expectations, if the verification is passed, it is deemed that the original code is not affected)

 

As we can see from the above, although unit testing has increased a considerable amount of development workload, for a long-term continuous improvement and maintenance project, unit testing is an effective way to reduce the overall cost. It can promptly and accurately find out whether all functions required by the Code are correct after the code is modified.

However, there is a serious defect here: unit testing cannot detect whether the modification of a method has an impact on other methods, you can only check whether the original purpose of the modified method is affected (this will be detailed in the following differences with the integration test)

Therefore, I personally think the most suitable scenario for unit testing is TDD-based development. If the requirement changes, a method is modified, and unit test code is also modified in most cases, because the expectation also changes, at this time, the impact on other Code cannot be detected, so unit testing is of little significance.

What is the difference between unit test and integration test?

Most people have never been able to distinguish between integration testing and unit testing. Even many people have always understood that unit testing can only be regarded as integration testing, but the concepts of the two are completely different.
Unit test objects are independent methods, and try to isolate methods and other methods as much as possible, as well as other external dependencies;

The testing objects in the grassroots test are the call relationships between methods and methods after the unit test detects, and whether the call execution process meets expectations.

    • Tests A project in one or all parts can span different categories and methods and directly access external resources. For example: file I/O, database operations, network connections ,...
    • Usually, you need to set the environment required for the (configure) test before performing the integration test. After the test is completed, you usually need to clear the residual information generated by the test to facilitate the next test or avoid affecting the results of other integration tests.

      • Classinitialize attribute

      • Classcleanup attribute

      •  

        Testinitialize attribute

      • Testcleanup attribute
        These attributes are often used in integration tests and cannot appear in unit tests.

Three basic elements of unit testing (trustworthiness/maintainability/readability)
  1. Trust your test code results
    • Can you trust your test results?
    • When it passes, we are confident that the tested code will work.

    • When it fails, it must prove that the tested code is wrong.

    • If you constantly lose confidence in the test results, you will not continue to write unit tests. Yes

    • Many people do not know the difference between unit test and integration test, so they feel that the unit test they write is too weak to trust the test results.

    • If you fail the test for some reason, it is not a good thing to directly change the code or test code. Your primary goal is to find out the main cause of the test failure, instead of simply looking at the error, you can trust your test program.

  2. Test code maintainability
    • Is your test program continuously maintained?
    • How can we effectively reduce the cost of maintaining test programs?
      PS: Some testable design pattern can effectively improve maintainability. Example: Repository pattern, service pattern ......
  3. Test code readability
      • Is the name of your test program easy to understand?
      • When a test fails, can you clearly identify the cause of the failure from the test method?

      • When people who read the test data do not understand your tests, they will not perform these tests or maintain these tests. Over time, they will get worse and worse.

     

    Test driven development & unit test

    At the end of this article, I have always thought that unit testing was actually born for the TDD development model. In this development mode, unit testing is completely smooth:

    1. Disassemble software functions according to Software Requirement documents and design functional modules;

    2. design unit test cases based on the required functional modules, because you can clearly understand what data can be provided and what functions can be achieved, this is sufficient for the design unit test cases;

    3. Write unit test code. At this time, you can focus on checking whether the method meets the design requirements. At this time, even the actual code has not been developed yet. net 4.0 dynamic keywords can be fully used here: calling methods that do not exist at all will not cause compilation failure.

    4. If you want to call other classes or methods to support the current method during unit testing, you can compile a mock object to simulate it, similarly, you do not need to implement real code. You only need to have a basic code framework or interface.

    5. After compiling the unit test code for this method, you can start to write the actual code for implementation, because in order to meet the needs of testability, the Code is based on the Dependency inversion model, so you no longer need to worry about whether other classes or methods to be called have been implemented or correctly. After compiling the implementation of this method, you can pass the unit test before running for acceptance.

    As you can see, if you develop in the above way, the code coupling is very low first, and the code quality is also very high, at last, the coupling between codes is low, which reduces the possibility of mutual progress impact during the development process. It is also advantageous when tracing bugs: it is easy to find out if the bugs are spreading.

    On the contrary, refactoring a legacy system to make it testable, and writing unit tests are actually a lot of work, and the actual benefits will not be very large.

     

    The basic concepts and values of unit testing are explained.ArticleThis section describes the unit test tools and environments in Visual Studio 2010.

     

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.