[英]Python unittest mocked method is called 0 times when it's being called at least once
[英]Unittest mocked class's method not being called
我是模擬測試的新手。 出於學習目的,我試圖模擬狀態檢查是否建立了數據庫連接,以及 Handler 嘗試執行數據庫連接操作的次數。
class Handler:
def is_connected(self):
# return true if connected to the backend database
pass
class Backend:
def initConnection(self):
handlr = Handler()
while(True):
is_connected = handlr.is_connected()
print(is_connected)
if(is_connected):
break
class TestBackendConnection(TestCase):
def test_connection_waiting(self):
"""Test that the backend waits for connection untill the handler connects"""
with patch('side_eff.Handler.is_connected') as isconn:
bknd = Backend()
isconn.side_effect = [False] * 4 + [True]
# print(tryCon()) => False
# print(tryCon()) => False
# print(tryCon()) => False
# print(tryCon()) => False
# print(tryCon()) => True
bknd.initConnection()
self.assertEqual(isconn.call_count, 5)
我正在用 side_effect 修補 Handler 類的is_connected方法,以便准備一個測試用例,這樣前四次嘗試沒有建立連接,而在第五次嘗試時建立連接。
盡管我嘲笑了該方法,但正在調用原始方法。
我的假設:
在對任何目標初始化模擬行為時,從新初始化的對象對此類目標進行的任何調用都會模仿修補時定義的模擬行為。
這是單元測試解決方案:
side_eff.py
:
class Handler:
def is_connected(self):
pass
class Backend:
def initConnection(self):
handlr = Handler()
while(True):
is_connected = handlr.is_connected()
print(is_connected)
if(is_connected):
break
test_side_eff.py
:
import unittest
from side_eff import Backend
from unittest.mock import patch
class TestBackendConnection(unittest.TestCase):
def test_connection_waiting(self):
"""Test that the backend waits for connection untill the handler connects"""
with patch('side_eff.Handler') as MockHandler:
handlerInstance = MockHandler.return_value
handlerInstance.is_connected.side_effect = [False] * 4 + [True]
bknd = Backend()
bknd.initConnection()
self.assertEqual(handlerInstance.is_connected.call_count, 5)
if __name__ == '__main__':
unittest.main()
帶有覆蓋率報告的單元測試結果:
(venv) ☁ python-codelab [master] ⚡ coverage run /Users/ldu020/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/59137518/test_side_eff.py
False
False
False
False
True
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
(venv) ☁ python-codelab [master] ⚡ coverage report -m
Name Stmts Miss Cover Missing
---------------------------------------------------------------------------
src/stackoverflow/59137518/side_eff.py 11 1 91% 4
src/stackoverflow/59137518/test_side_eff.py 13 0 100%
---------------------------------------------------------------------------
TOTAL 24 1 96%
源代碼: https : //github.com/mrdulin/python-codelab/tree/master/src/stackoverflow/59137518
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.