简体   繁体   中英

Testing instance methods in Python using mock

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!

You can use patch.object() to patch the a() method of TestClass .

Eg

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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM