跳过Python中对模拟对象的第一次调用

跳过Python中对模拟对象的第一次调用,python,unit-testing,mocking,Python,Unit Testing,Mocking,这是我的函数代码,它的单元测试在两个单独的try块中测试相同的函数,不同输入的块除外: 脚本: from file import myfunction in main: try: myfunction(str_input_1) except Exceptoin as e: print("error str_input_1") try: myfunction(str_input_2) except Exceptoin as e: print("error str

这是我的函数代码,它的单元测试在两个单独的try块中测试相同的函数,不同输入的块除外:

脚本:

from file import myfunction

in main:
try:
    myfunction(str_input_1)
except Exceptoin as e:
    print("error str_input_1")

try:
    myfunction(str_input_2)
except Exceptoin as e:
    print("error str_input_2")
单独文件中的单元测试:

@补丁(myfunction)
def调用_myfunction_和_str_input_1(self、mock_myfunction):
mock_myfunction.side_effect=异常(“错误str_输入_1”)
myfunction(str_输入_1)
mock_myfunction.assert_调用了(str_input_1)
@补丁(myfunction)
def调用_myfunction_和_str_input_2(self、mock_myfunction):
myfunction(str_输入_2)
mock_myfunction.assert_调用了(str_input_2)
第一个测试用例通过得很好,但第二个单元测试也尝试使用第一个单元测试的值运行它:

raise AssertionError(_error_message()) from cause
AssertionError: Expected call: myfunction(str_input_2)
Actual call: myfunction(str_input_1)
改变

@补丁(myfunction)
def调用_myfunction_和_str_input_2(self、mock_myfunction):
myfunction(str_输入_2)
mock_myfunction.assert_调用了(str_input_2)
致:

@补丁(myfunction)
def调用_myfunction_和_str_input_2(self、mock_myfunction):
mock_myfunction.side_effect=[
无,#调用str#u输入#u 1
异常(异常错误),#调用str_输入2
]
myfunction(str_输入_2)
mock_myfunction.assert_调用了(str_input_2)

解决了问题。

您是否在顶级范围内定义了
mock\u myfunction
?如果是这样,那么这两个函数中的对象是相同的,因此调用是累积的。为每个测试创建一个新的模拟对象。使用夹具使其干燥。@jordanm:请检查更新的脚本,我将函数从另一个文件导入主文件。脚本与测试有什么关系,由于您在测试中直接调用了
myfunction
?@chepner:脚本显示了调用函数的顺序和结构,作为第二个单元测试,该函数需要通过除块之外的第一次尝试。请阅读。你现在拥有的东西并不完整(甚至不可运行)。