In my attempt to learn TDD, trying to learn unit testing and using mock with python. Slowly getting the hang of it, but unsure if I\'m doing this correctly. Forewarned: I\
I'd like to point out a variation of the accepted answer in which a new
argument is passed to the patch()
decorator:
from unittest.mock import patch, Mock
MockSomeClass = Mock()
@patch('mymodule.SomeClass', new=MockSomeClass)
class MyTest(TestCase):
def test_one(self):
# Do your test here
Note that in this case, it is no longer necessary to add the second argument, MockSomeClass
, to every test method, which can save a lot of code repetition.
An explanation of this can be found at https://docs.python.org/3/library/unittest.mock.html#patch:
If
patch()
is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function.
The answers above all omit new, but it can be convenient to include it.