0

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!

1
  • 1
    You mock the whole class, so everything called for that class will just return a mock and not call the real method (like b in your case). You have to mock specifically a instead (e.g. patch("test_file.TestClass.a")). Commented Mar 19, 2021 at 19:48

1 Answer 1

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%
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.