我正在尝试使用模拟库来测试一段代码。在此代码中,用户原始输入在 for 循环中被接受,如下所示。我已经写了测试用例test_apple_record
可以为托盘编号提供单个用户输入值。
但是,对于 for 循环中的每次迭代,它只采用与预期相同的值 (5)。
问题是:如何为每次迭代提供不同的值?例如,当i=0、1和2时,托盘编号的具体值分别为5、6和7。
class SomeClass(unittest.TestCase):
def apple_counter(self):
apple_record = {}
for i in range(3):
apple_tray = input("enter tray number:")
apple_record[apple_tray] = (i+1)*10
print("i=%d, apple_record=%s"%(i, apple_record))
def test_apple_record(self):
with mock.patch('builtins.input', return_value='5'):
self.apple_counter()
您可以使用side_effect
带有可迭代的参数以提供返回值:
with mock.patch('builtins.input', side_effect=[5, 6, 7]):
self.apple_counter()
See the docs https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock:
If 副作用是一个可迭代对象,那么每次调用模拟都会返回可迭代对象的下一个值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)