Unit Testing - Personal Experience

    About five years ago, I learned about unit testing. Like any normal programmer, he fired up on the idea and rushed to implement it, simultaneously re-reading a bunch of enthusiastic theory and skeptical criticism. So, practical experience of applying the technology in real life, in large-scale working projects was gradually accumulating.

    But personal experience has shown that, unfortunately, I did not immediately understand from theory: poorly designed code is almost impossible to automatically test , and vice versa - the intention to test the code forces you to design the architecture more competently. .



    Let me explain right away - by “good architecture” I mean dividing the system into weakly dependent modules (layers), in which the system remains stable after changes inside the modules.

    And I noticed this as follows: I begin to write code with the desire to cover it with unit tests. In another situation, I would roll several pages of govnokod if only it worked and performed what was required. But because of the intention to use unit tests, you have to allocate interfaces, create all separate services, abstract from the UI, apply all sorts of patterns like IoC, DependencyInjection, which weaken the system’s connectivity, etc.

    I know the idea of ​​writing tests first. and then the code, and at first did it. But when the amount of code is very large, this is no longer the case. As a result, I began to write tests only when errors were detected in the code. I malfunctioned the method - I am writing a test on it. There are no glitches - I do not write. Thus, I seem to implement the rule "do not write tests for trivial code."

    But, despite the fact that there are few unit tests, the code is ready for any class or method to be tested if necessary.

    And it is precisely this desire for the potential for writing unit tests that sets the bottom line for application design quality .

    It happened to work with the inherited code - it was necessary to maintain and improve it. Usually it turned out that it was a “can with worms” - everything was interconnected there so that changes in one place responded in other unpredictable ways in other places. A natural desire arose (in science, as in books) before changing such a code to cover it with tests. But how to cover it, if, to create an instance of a class, it happens, you need to create a dozen other classes that still drag a hundred others? And even mocks do not always help. So it turns out that it is extremely difficult to create complete tests for complicated code - it was not originally intended for this .

    More on the topic: article habrahabr.ru/blogs/development/51706

    Summary: write the code as if you were actually going to cover it with unit tests :)

    Also popular now: