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塊也是如此。
添加回答
舉報