有一个变量的抽象类。它有一个_callbacks方法,用于在值发生变化时执行控制器类提供的函数。我想为它写一个测试。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
提交
取消