有一個變量的抽象類。它有一個_callbacks方法,用于在值發(fā)生變化時執(zhí)行控制器類提供的函數。我想為它寫一個測試。from unittest.mock import Mockclass Variable(): def __init__(self, value=0): self.value = value self.callbacks = {} def add_callback(self, func): self.callbacks[func] = None def _callbacks(self): for func in self.callbacks: func(self.value)def test_var_add_callback(): func = Mock() var = Variable() var.add_callback(func) var._callbacks() assert func.assert_called()使用 pytest 可以得到:================================== FAILURES ===================================____________________________ test_var_add_callback ____________________________ def test_var_add_callback(): func = Mock() var = Variable() var.add_callback(func) var._callbacks()> assert func.assert_called()E AssertionError: assert NoneE + where None = <bound method NonCallableMock.assert_called of <Mock id='2389330693592'>>()E + where <bound method NonCallableMock.assert_called of <Mock id='2389330693592'>> = <Mock id='2389330693592'>.assert_calledtests\test_stack.py:25: AssertionError===================== 1 failed, 18 passed in 0.40 seconds =====================我不明白為什么它不起作用。我閱讀了理解 Python 模擬對象庫#斷言和檢查,我很確定我正在做與示例中相同的事情。None此外,即使我func手動調用,斷言也會返回def test_var_add_callback():
func = Mock()
var = Variable()
var.add_callback(func)
var._callbacks()
func()
assert func.assert_called()請幫我找到我缺少的東西。
1 回答

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
只需刪除語句assert
前的關鍵字即可func.assert_called()
。
func.assert_called()
返回None
,assert None
將提高AssertionError
.
添加回答
舉報
0/150
提交
取消