简体   繁体   中英

unittest mock how to mock a method being called

I want to test that method a calls method b . These methods are in separate files, and are not a part of class object.

# file_a.py
from file_b import b

def a():
    b()
# file_b.py
def b():
    test
import unittest
from unittest import mock

from file_a import a

class MyTestCase(unittest.TestCase):
    @mock.patch('file_b.b')
    def test_b_called(self, mock):
        a()
        mock.assert_called()

if __name__ == "__main__":
    unittest.main()

This fails with AssertionError: Expected 'b' to have been called.

Is there a right way to do this?

When you import a function into the current namespace, like in your example, the function will need to be patched in that namespace. In your case, you need:

@mock.patch('file_a.b')

You would patch file_b.b if you had done the import and use like this:

import file_b
def a():
    file_b.b()

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