大家好!
这可能是一个关于unittest.mock.patch()
和unittest.mock.patch.object()
的区别的问题,下面的代码使用mock.patch.object()
时,可以正常运行,我不明白为什么使用mock.patch()
的时候,会报错ModuleNotFoundError: No module named 'Person'
,这种情况是一定不能用mock.patch()
吗?
# py_unittest.py
from unittest import TestCase
from unittest.mock import patch
from unittest import main
class Person(object):
def __init__(self, name):
self.name = name
def print_name(self):
print('My name is ' + self.name)
def print_parents(self):
mother = input("Enter mother's name: ")
father = input("Enter father's name: ")
print("{}'s parents are {} and {}.".format(self.name, mother, father))
self.fake_func()
def fake_func(self):
pass
class FuncTest(TestCase):
def test_print_parents(self):
john = Person('John')
with patch('builtins.input') as mocked_input:
mocked_input.side_effect = ('Jo', 'Lee')
with patch('builtins.print') as mocked_print:
with patch.object(Person, "fake_func") as mocked_fake_func:
# with patch('Person.fake_func') as mocked_fake_func: 如果启用这段代码会报错 ModuleNotFoundError: No module named 'Person'
john.print_parents()
mocked_print.assert_called_with("John's parents are Jo and Lee.")
mocked_fake_func.assert_called_once()
if __name__ == '__main__':
main()
查询了下,还是使用
mock.patch()
的时候,查找module的问题,修改了下,现在可以正常运行了。代码结构:
person(目录)
person.py
的代码__init__.py
的代码py_unittest.py
的代码