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!
asked Mar 19, 2021 at 11:12
km6
2,5702 gold badges17 silver badges18 bronze badges
1 Answer 1
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%
answered Mar 22, 2021 at 2:47
Lin Du
104k139 gold badges341 silver badges576 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-py
ainstead (e.g.patch("test_file.TestClass.a")).