1 回答

TA贡献1797条经验 获得超6个赞
你的第一个问题是跳出循环。print您可以通过向引发异常的模拟函数添加副作用来做到这一点,并在测试中忽略该异常。mockedprint也可用于检查打印的消息:
@patch('randomgame.print')
@patch('randomgame.input', create=True)
def test_params_input_1(self, mock_input, mock_print):
mock_input.side_effect = ['foo']
mock_print.side_effect = [None, Exception("Break the loop")]
with self.assertRaises(Exception):
main()
mock_print.assert_called_with('You need to enter a number!')
请注意,您必须将副作用添加到第二个 print调用,因为第一个调用用于发出欢迎消息。
第二个测试的工作方式完全相同(如果以相同的方式编写),但有一个问题:在您的代码中,您捕获的是通用异常而不是特定异常,因此您的“中断”异常也将被捕获。这通常是不好的做法,因此与其解决此问题,不如捕获转换int失败时引发的特定异常:
while True:
try:
low_param = int(input('Please enter the lower number: '))
high_param = int(input('Please enter the higher number: '))
if high_param <= low_param:
print('No, first the lower number, then the higher number!')
else:
break
except ValueError: # catch a specific exception
print('You need to enter a number!')
代码中的第二个try/catch块也是如此。
添加回答
举报