Як правильно робити Dependency Injection, щоб легко Unit-тестувалося?
Я розмістив запитання на stackoverflow, але там довго треба чекати і відповіді інколи дивні.
Надіюся швидше буде нормальна відповідь тут.
======
I am going to add Unit testing for my Python application.
I need to understand how to do a unit testing for methods where some object is created and something is called from it. I need to replace such objects with some injected objects instead of creation. And inject a Mock in my test.
Example of pseudo code
To test this with unit tests i will need to inject the mock object of RandomOperationSelector.
Best practices i have found on the web suggest me to do like this
Or as alternative
But for me this is not acceptable. I do not want to care about creation of the instance of RandomOperationSelector every time when i want to use MyClass. Because in reality there are usually more classes used in a class.
So, there is my question. Is it acceptable to use injections like this example below. Can it be considered as a good practice?
On production i will not do any injections and the class will create that object itself. But on testing i will call set_operation_selector() to inject an object mock.
And same functions to add for every related class.
And another question. Is there some pattern to use a single place to “build objects”? Example,
Here i have some class ObjectsBuilder and we usually have only one instance of this class. It is used as a property in ANY object in my application. ANY object would refer to it to create other objects (or reuse existent if it was set somewhere else)
In unit tests we will always inject all required mocks before calling some method from some object. So, instead of creation it will use existent.
On production there would not be injected objects and it would create itself.
Disadvantage is that every class must have a standard constructor (with a specific argument). And additional data should be added with setters.
Is this acceptable? Any pros/cons?
==========================
Загалом питання в тому де створювати обʼєкти класів, щоб можна було легко тестувати окремі методи з допомогою моків.
4 коментарі
Додати коментар Підписатись на коментаріВідписатись від коментарів