所以,基本上我想模拟一个在另一个类中导入的函数,由于某种原因,我无法在不调用模拟的返回值的情况下检索模拟结果。
这是设置:一个文件,一个模块,一个测试类。我想在 source.fileB 中模拟 functionB()。
源文件B
def functionB():
print('toto')
源文件A
from source.fileB import *
def functionA():
print("bar")
return functionB()
测试用例
from source.fileA import functionA
from source.fileA import functionB
@mock.patch('source.fileA.functionB')
def test_functionA(functionB_mock):
functionB_mock().returnvalue = "foo"
print(functionB_mock) # prints MagicMock object named functionB
print(functionB_mock.returnvalue) # prints MagicMock object name functionB.returnvalue
print(functionB_mock().returnvalue) #prints "foo"
print(functionA().returnvalue) #executes functionA, prints both "bar" and "foo"
print(functionA()) #executes functionA, prints both "bar" and MagicMock object named functionB()
因此,每次我尝试获取模拟的 functionB() 的结果时,都必须使用返回值。这让我发疯,因为我无法更新 functionA()
return functionB().returnvalue
为了让被测代码的其余部分正确执行。我一定是做错了什么,但我无法准确理解是什么。
有两个问题:
return_value
,不是returnvalue
!这是带有修复程序和一些解释性注释的测试代码的独立(单文件)版本。
import mock
def functionB():
print('toto')
def functionA():
print("bar")
return functionB()
@mock.patch('__main__.functionB')
def test_functionA(functionB_mock):
functionB_mock.return_value = "foo"
# Prints a mock object because that's what functionB_mock is.
print(functionB_mock)
# Prints another MagicMock object because every
# attribute of a mock is another mock.
print(functionB_mock.return_value)
# The following two lines would raise AttributeError because
# "foo" isn't a Mock and doesn't have a 'return_value' attribute!
# print(functionB_mock().return_value)
# print(functionA().return_value)
# Executes functionA, prints "bar" and "foo"
print(functionA())
test_functionA()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句