Test double: dummy, fake, stub, mock
Test doubles = faking before testing. Use mocking or stubbing when your code uses external dependencies like system calls, or accessing a database. To create independent tests and run more quickly.
Fake is used when prod code is not ready. It is imitating. Similar to stub.
Stub is incoming, for getting input.
Mock is out-coming, making request to other dependencies to change their state. Mock is saving what calls were made.
Mocks
- Моки помогают имитировать и изучать исходящие (out coming) взаимодействия. То есть вызовы, совершаемые тестируемой системой (SUT) к ее зависимостям для изменения их состояния.
- Mocking means creating a fake version of an external or internal service that can stand in for the real one. Helping your tests run more quickly and more reliably.
- It allows you to replace parts of your system under test with mock objects.
- Mocks are objects that register calls they receive. In test assertion we can verify on Mocks that all expected actions were performed.
- Python has
MockandMagicMockclasses to create mocks. MagicMock as an extended version of Mock. MagicMock has the implementation of magic methods.
The Mock objects record all interactions with them and you can then inspect these interactions.
# Attaching mock attribute to an existing object
class ProductionClass: pass
mock = mock.Mock(name='foo', return_value='bar')
thing = ProductionClass()
thing.method = mock
thing.method(1, 2, k='v') #=> 'bar'
mock.call_args_list #=> [call(1, 2, k='v')]
mock.method_calls #=> []The patch()function looks up an object in a given module and replaces it with another object. Replaced with MagicMock.
Stubs
- Стабы помогают имитировать входящие (incoming) взаимодействия. То есть вызовы, совершаемые SUT к ее зависимостям для получения входных данных.
- Stub is an object that holds predefined data and uses it to answer calls during tests.
Difference between stub and mock
Mock: Например, отправка электронной почты является исходящим (out going) взаимодействием: это взаимодействие приводит к побочному эффекту на SMTP-сервере. Тестовый двойник, имитирующий такое взаимодействие, - это мок.
Stub: Извлечение данных из БД является входящим (incoming) взаимодействием — оно не приводит к побочному эффекту. Соответствующий тестовый двойник является стабом.
References
- https://habr.com/ru/post/577424/ mock vs stub vs fake
- https://medium.com/geekculture/right-way-to-test-mock-and-patch-in-python-b02138fc5040
- https://alpopkes.com/posts/python/mocking/ Check other blogs and
- Watch https://www.youtube.com/watch?v=ww1UsGZV8fQ and https://www.youtube.com/watch?v=Ldlz4V-UCFw and https://www.youtube.com/watch?v=rk-f3B-eMkI
- https://docs.python.org/3/library/unittest.mock.html
- https://realpython.com/python-mock-library/
- https://circleci.com/blog/how-to-test-software-part-i-mocking-stubbing-and-contract-testing/