import unittest
from unittest.mock import patch
class MyTestCase(unittest.TestCase):
def test_my_method(self):
self.assertEqual(1, 1)
@patch('my.module.program.func')
def test_my_method_with_path(self, mock_func):
mock_func.return_value = 3
if __name__ == '__main__':
unittest.main()
We should always patch the variables in the scope of the program we’re testing, even if itself imported them from somewhere else. Example:
my/module/program.py
:
from lib import func
It imported func
from lib
.
test.py
:
...
@patch('my.module.program.func')
def test_my_method(self, mock_func):
pass
We patch func
from my.module.program
, not lib
.
If we assign a list to side_effect
it returns the i-th value each time the function is called.
my/module/program.py
:
def f():
return 1
def g():
print(f(), f(), f())
from my.module.program import g
...
@patch('my.module.program.f')
def test_my_method(self, mock_func):
mock_func.side_effect = [1, 2, 3]
g() # prints 1 2 3
Assign a function to side_effect
:
def f(i):
return i
def g(i):
print(f(i))
from my.module.program import g
...
@patch('my.module.program.f')
def test_my_method(self, mock_func):
def mock_func_impl(i):
return i*2
mock_func.side_effect = mock_func_impl
g(3) # prints 6
Assign a function to side_effect
:
from my.module.program import g
...
@patch('my.module.program.f')
def test_my_method(self, mock_func):
mock_func.side_effect = RuntimeError()
g(3) # throws