返回

单元测试不应缺席的可靠性

闲谈

Unit testing is an integral part of software development, but in a real project, no matter how you organize the tests and how many types of tests are added, including unit tests and integration tests, if the tests are not reliable, easy to maintain, or easy for others to read, then they cannot bring any value. So, in order to evaluate whether a test is a good unit test, there are three important pillars:

  • Reliability
    Developers hope that tests can be reliable, if a change in the code is detected by the test, it means that the change breaks the behavior of the code; on the other hand, if the test does not detect the change, it means that the test is not reliable.

  • Maintainability
    Maintainability refers to the cost of maintaining and updating tests when the code changes. For example, if a test is too fragile and is easily broken by a small change in the code, then the test is not maintainable and will increase the cost of maintaining the code.

  • Readability
    Readability refers to how easy it is for other people to understand the test. If a test is not readable, it is difficult for others to understand the test logic, which will also increase the cost of maintaining the code.

A good unit test should have the following characteristics:

  • The test should be repeatable. This means that the test should produce the same result every time it is run, regardless of the order in which the tests are run or the state of the system.

  • The test should be isolated. This means that the test should not rely on other tests or external factors, such as the state of the database or the file system.

  • The test should be atomic. This means that the test should test a single unit of functionality.

  • The test should be fast. This means that the test should run quickly, so that it can be easily run frequently.

  • The test should be easy to read and understand. This means that the test should be written in a clear and concise style, and should use descriptive variable names and comments.

If you can follow these principles, you can write unit tests that are reliable, maintainable, and readable, and that will help you to improve the quality of your software.