What is unit testing?
Unit tests that verify that your application can run as expected.
Mainly through the Mock or Stub mechanism to isolate the dependencies between other components / services, control the boundaries of the test, so as a single class or code to check and test methods.
Why need unit testing?
Because each unit (class or method) is the cornerstone of the whole system.
When beginning of the unit test, although the short term to the programming efficiency of the impact, but since the beginning of the unit test, the quality of the project will be improved, thus avoiding the late maintenance and modify the cost of defects, so from a long-term perspective, Implementing unit testing can help improve project productivity.
And because the implementation of unit testing, the problem will be identified in advance, changed the previous unit test, all the problems are focused on the final outbreak of the project drawbacks.
From the above we can be sure: Unit testing = improve quality + improve programming efficiency + reduce development and test costs + improve the workflow
Unit testing brings the benefits
1. bring higher test coverage: unit testing can easily simulate the wrong conditions, simulate a variety of possible situations, thereby improving the robustness of the code.
2. Improve team efficiency: Unit testing allows you to submit high quality / tested code before "functional testing" to avoid problems with overall functional testing, thus avoiding the need for repetitive changes.
3. Help to monitor: a group of successful unit tests can confirm that your code can run correctly, or when you do wrong to remind you in a timely manner.
4. Reduce debugging: A good set of unit tests will reduce the chance of debugging applications looking for errors and the time spent.
5. Confidence in refactoring: If there is no unit test, it is a very difficult thing to prove whether the refactoring is successful or not. The unit test provides a safety net that provides confidence in your refactoring.
6. Find the parts that need to be improved: through the management unit test, you can find out whether the code being tested have a design problem, whether you need to improve the code, or whether you need to refactor.
7. Provide the perfect code example: The unit test can perfectly provide an example of how the code in the application is used and provided to other developers.
8. Enable code coverage and other metrics: Provide data such as code coverage, code performance, and application execution speed.
Unit testing isolation depends on two mechanisms
Stub: used to simulate an external dependency.
Mock: used to shield an external dependency.
Note: In unit testing, we are always accustomed to using these two mechanisms to isolate external dependencies, but please avoid excessive isolation, which will lead to lower test integrity, resulting in when external dependencies change, your test code also Not detected.
Reference