本文介紹了python在單元測試中模擬原始輸入的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
假設(shè)我有這個(gè) python 代碼:
Suppose I have this python code:
def answer():
ans = raw_input('enter yes or no')
if ans == 'yes':
print 'you entered yes'
if ans == 'no':
print 'you entered no'
如何為此編寫單元測試?我知道我必須使用模擬",但我不明白如何.誰能舉個(gè)簡單的例子?
How do I write a unittest for this ? I know i have to use 'Mock' but I don't understand how. Can anyone make some simple example ?
推薦答案
你不能給輸入打補(bǔ)丁,但是你可以把它包裝起來使用 mock.patch().這是一個(gè)解決方案:
You can't patch input but you can wrap it to use mock.patch(). Here is a solution:
from unittest.mock import patch
from unittest import TestCase
def get_input(text):
return input(text)
def answer():
ans = get_input('enter yes or no')
if ans == 'yes':
return 'you entered yes'
if ans == 'no':
return 'you entered no'
class Test(TestCase):
# get_input will return 'yes' during this test
@patch('yourmodule.get_input', return_value='yes')
def test_answer_yes(self, input):
self.assertEqual(answer(), 'you entered yes')
@patch('yourmodule.get_input', return_value='no')
def test_answer_no(self, input):
self.assertEqual(answer(), 'you entered no')
請(qǐng)記住,此代碼段僅適用于 Python 3.3+ 版本
Keep in mind that this snippet will only work in Python versions 3.3+
這篇關(guān)于python在單元測試中模擬原始輸入的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!