Reputation: 2540
I have a class similarly structured to this:
class TestClass:
def a(self):
pass
def b(self):
self.a()
I want to test if running TestClass().b()
successfully calls TestClass().a()
:
class TestTestClass(unittest.TestCase):
def test_b(self):
with patch('test_file.TestClass') as mock:
instance = mock.return_value
TestClass().b()
instance.a.assert_called()
However, it fails because a
isn't called. What am I doing wrong? I went through the mock documentation and various other guides to no avail.
Thanks!
Upvotes: 0
Views: 273
Reputation: 102587
You can use patch.object() to patch the a()
method of TestClass
.
E.g.
test_file.py
:
class TestClass:
def a(self):
pass
def b(self):
self.a()
test_test_file.py
:
import unittest
from unittest.mock import patch
from test_file import TestClass
class TestTestClass(unittest.TestCase):
def test_b(self):
with patch.object(TestClass, 'a') as mock_a:
instance = TestClass()
instance.b()
instance.a.assert_called()
mock_a.assert_called()
if __name__ == '__main__':
unittest.main()
unit test result:
⚡ coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/66707071/test_test_file.py && coverage report -m --include='./src/**'
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Name Stmts Miss Cover Missing
----------------------------------------------------------------------------
src/stackoverflow/66707071/test_file.py 5 1 80% 3
src/stackoverflow/66707071/test_test_file.py 12 0 100%
----------------------------------------------------------------------------
TOTAL 17 1 94%
Upvotes: 1