1 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
你的第一個(gè)問(wèn)題是跳出循環(huán)。print您可以通過(guò)向引發(fā)異常的模擬函數(shù)添加副作用來(lái)做到這一點(diǎn),并在測(cè)試中忽略該異常。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!')
請(qǐng)注意,您必須將副作用添加到第二個(gè) print調(diào)用,因?yàn)榈谝粋€(gè)調(diào)用用于發(fā)出歡迎消息。
第二個(gè)測(cè)試的工作方式完全相同(如果以相同的方式編寫(xiě)),但有一個(gè)問(wèn)題:在您的代碼中,您捕獲的是通用異常而不是特定異常,因此您的“中斷”異常也將被捕獲。這通常是不好的做法,因此與其解決此問(wèn)題,不如捕獲轉(zhuǎn)換int失敗時(shí)引發(fā)的特定異常:
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!')
代碼中的第二個(gè)try/catch塊也是如此。
添加回答
舉報(bào)