有一个变量的抽象类。它有一个_callbacks方法,用于在值发生变化时执行控制器类提供的函数。我想为它写一个测试。
from unittest.mock import Mock
class 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 None
E + 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_called
tests\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()
请帮我找到我缺少的东西。
蝴蝶刀刀
相关分类