我在 Python 中遇到单元测试问题。具体来说,当我尝试模拟我的代码导入的函数时,分配给该函数输出的变量被分配给一个 MagicMock 对象,而不是模拟函数的 return_value。我一直在研究 python 的 unittest 库的文档,但没有任何运气。
以下是我要测试的代码:
from production_class import function_A, function_B, function_M
class MyClass:
def do_something(self):
variable = functionB()
if variable:
do_other_stuff()
else:
do_something_else
这是我尝试过的:
@mock.patch(path.to.MyClass.functionB)
@mock.patch(<other dependencies in MyClass>)
def test_do_something(self, functionB_mock):
functionB_mock.return_value = None # or False, or 'foo' or whatever.
myClass = MyClass()
myClass.do_something()
self.assertTrue(else_block_was_executed)
我遇到的问题是,当测试进入variable = functionB
MyClass 时,变量没有设置为我的返回值;它被设置为一个 MagicMock 对象(因此 if 语句总是计算为 True)。如何模拟导入的函数,以便在执行时变量实际上设置为返回值而不是 MagicMock 对象本身?