Python的單元測試unittest中的Mock使用小結
阿新 • • 發佈:2019-01-01
前面一篇博文簡單說了使用unittest.mock
對無返回值的函式做單元測試。這裡是更多一些例子的總結。
被測函式中使用到了input需要自動化輸入
#!/usr/bin/env python3
from unittest import TestCase
from unittest.mock import patch
from unittest import main
def func_input():
name = input("Enter your name: ")
print('Your name is {}'.format(name))
def test_func_input ():
with patch('builtins.input') as mocked_input:
mocked_input.side_effect = ('Jo',) #當input的時候會輸入Jo
with patch('builtins.print') as mocked_print:
func_input()
mocked_print.assert_called_with('Your name is Jo')
if __name__ == '__main__':
main()
需要驗證函式是否被“被測函式“呼叫
#!/usr/bin/env python3
from unittest import TestCase
from unittest.mock import patch
from unittest import main
def func_1():
func_2()
def func_2():
print("It's func 2!")
def test_func_1():
with patch('func_2') as mocked_func_2:
func_1()
mocked_func_2.assert_called_once() #斷言mocked_func_2被呼叫過一次,在執行func_1()後
if __name__ == '__main__':
main()
mock.patch()和mock.patch.object()的區別
這一塊我還不是特別明白,搜尋了下,大致區別如下
mock.patch() doesn’t require that you import the object before patching, while mock.patch.object() does require that you import before patching
有一個遺留問題,如下程式碼中,完全不能使用mock.patch()嗎?
# py_unittest.py
from unittest import TestCase
from unittest.mock import patch
from unittest import main
class Person(object):
def __init__(self, name):
self.name = name
def print_name(self):
print('My name is ' + self.name)
def print_parents(self):
mother = input("Enter mother's name: ")
father = input("Enter father's name: ")
print("{}'s parents are {} and {}.".format(self.name, mother, father))
self.fake_func()
def fake_func(self):
pass
class FuncTest(TestCase):
def test_print_parents(self):
john = Person('John')
with patch('builtins.input') as mocked_input:
mocked_input.side_effect = ('Jo', 'Lee')
with patch('builtins.print') as mocked_print:
with patch.object(Person, "fake_func") as mocked_fake_func:
# with patch('Person.fake_func') as mocked_fake_func: 啟用這裡的話,會報
# 錯 ModuleNotFoundError: No module named 'Person'
john.print_parents()
mocked_print.assert_called_with("John's parents are Jo and Lee.")
mocked_fake_func.assert_called_once()
if __name__ == '__main__':
main()