Unit tests - The benefit from unit tests with contract changes?

前端 未结 9 1158
無奈伤痛
無奈伤痛 2021-01-30 00:27

Recently I had an interesting discussion with a colleague about unit tests. We were discussing when maintaining unit tests became less productive, when your contracts change.

9条回答
  •  梦毁少年i
    2021-01-30 00:53

    The first issue you raise is the so-called "fragile test" problem. You make a change to your application, and hundreds of tests break because of that change. When this happens, you have a design problem. Your tests have been designed to be fragile. They have not been sufficiently decoupled from the production code. The solution is (as it it in all software problems like this) to find an abstraction that decouples the tests from the production code in such a way that the volatility of the production code is hidden from the tests.

    Some simple things that cause this kind of fragility are:

    • Testing for strings that are displayed. Such strings are volatile because their grammar or spelling may change at the whim of an analyst.
    • Testing for discrete values (e.g. 3) that should be encoded behind an abstraction (e.g. FULL_TIME).
    • Calling the same API from many tests. You should wrap the API call in a test function so that when the API changes you can make the change in one place.

    Test design is an important issue that is often neglected by TDD beginners. This often results in fragile tests, which then leads the novices to reject TDD as "unproductive".

    The second issue you raised was false positives. You have used so many mocks that none of your tests actually test the integrated system. While testing independent units is a good thing, it is also important to test partial and whole integrations of the system. TDD is not just about unit tests.

    Tests should be arranged as follows:

    • Unit tests provide close to 100% code coverage. They test independent units. They are written by programmers using the programming language of the system.
    • Component tests cover ~50% of the system. They are written by business analysts and QA. They are written in a language like FitNesse, Selenium, Cucumber, etc. They test whole components, not individual units. They test primarily happy path cases and some highly visible unhappy path cases.
    • Integration tests cover ~20% of the system. They tests small assemblies of components as opposed to the whole system. Also written in FitNesse/Selenium/Cucumber etc. Written by architects.
    • System tests cover ~10% of the system. They test the whole system integrated together. Again they are written in FitNesse/Selenium/Cucumber etc. Written by architects.
    • Exploratory manual tests. (See James Bach) These tests are manual but not scripted. They employ human ingenuity and creativity.

提交回复
热议问题