📜 ⬆️ ⬇️

Unit Testing - Personal Experience

About five years ago I learned about unit testing. Like any normal programmer, he caught on the idea and rushed to implement it, at the same time he re-read a bunch of enthusiastic theory and skeptical criticism. So gradually accumulated practical experience in the use of technology in real life, in large work projects.

But personal experience showed that, unfortunately, I did not immediately understand from the theory: poorly designed code is almost impossible to automatically test , and vice versa - the intention to test the code makes it more competent to design the architecture. .


')
I’ll explain right away that by “good architecture” I mean the division of 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 start writing code with a desire to cover it with unit tests. In another situation, I would roll a few pages of govnokod, just to work and do what is required. But because of the intention to use unit tests, it is necessary to allocate interfaces, create separate services for all, abstract from the UI, use all sorts of IoC, DependencyInjection patterns that weaken the connectivity of the system, etc.

I know the idea about what you need to write tests first, and then the code, and at first it did. But when the amount of code is very large - no longer up to it. As a result, I began writing tests only when errors are detected in the code. Zagluchil method - I write a test on it. There are no glitches - I do not write. Thus, I kind of implement the rule “do not write tests for trivial code”.

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

And it is precisely this desire for the potential possibility of writing unit tests that sets the lower bar for the quality of application design .

It happened to work with legacy code - it was necessary to maintain and improve it. It was usually found out that this is a “bank with worms” - everything is interconnected there, so that changes in one place responded in unpredictable ways in other places. There was a natural desire (for science, as in books) before changing such a code to cover it with tests. But how to cover, if to create an instance of a class, it happens that you need to create a dozen other classes that still pull hundreds of others? And even mocks do not always help. So it turns out that it is extremely difficult to create full-fledged tests for confusing 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 are actually going to cover it with unit tests :)

Source: https://habr.com/ru/post/110909/


All Articles