I suppose your production code is contained in the following file prod.py
:
class A:
def someFunction(self):
print("does work")
class B:
def __init__(self): # <--- here in your code you miss the self argument
self.instance_a = A()
A possible test code which mocks the method someFunction()
of the class A
is the following:
import unittest
from unittest import mock
from prod import B
# this function is used for mocking the method someFunction()
def someFunction_mocked():
print('some function mocked')
class MyTestCase(unittest.TestCase):
# the following method uses the production code
def test_something(self):
sut = B()
sut.instance_a.someFunction()
# the following method substitute the object points by instance_a by a Mock object
def test_something_2(self):
sut = B()
with mock.patch.object(sut, 'instance_a') as mock_a:
mock_a.someFunction.side_effect = someFunction_mocked
sut.instance_a.someFunction()
if __name__ == '__main__':
unittest.main()
The test code is saved in the same folder of the file prod.py
. The function someFunction()
is substituted by the function someFunction_mocked()
which prints the message some function mocked
instead the message does work
.
The output of the execution of the test code is:
does work
some function mocked
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
where the output is produces as following:
- the message
does work
is printed by the test method test_something()
- the message
some function mocked
is printed by the test method test_something_2()
. In this second method is present the instruction mock.patch.object()
which performs the mocking.