使用Python unittest测试回调调用的正确方法是什么?
我有一个如下所示的应用程序代码使用Python unittest测试回调调用的正确方法是什么?,python,unit-testing,python-3.x,callback,Python,Unit Testing,Python 3.x,Callback,我有一个如下所示的应用程序代码 # Filename: app.py class Foo: def __init__(self): self.callback = None def set_handler(self, callback): self.callback = callback def run(self, details): name, age = details.split('/') if a
# Filename: app.py
class Foo:
def __init__(self):
self.callback = None
def set_handler(self, callback):
self.callback = callback
def run(self, details):
name, age = details.split('/')
if age.isdigit():
age = int(age)
else:
age = -1
return self.callback(name, age)
如您所见,它提供了一个set\u处理程序
方法来设置回调。稍后必须使用两个参数调用回调:字符串和整数。我试图在单元测试中确保这一点
# Filename: test_app.py
import unittest
from app import Foo
class AppTest(unittest.TestCase):
def f(self, a, b):
# This callback should get called with the first argument as
# string and the second argument as integer
return repr(a) + ',' + repr(b)
def test_callback(self):
foo = Foo()
foo.set_handler(self.f)
self.assertEqual(foo.run('John/20'), "'John',20")
self.assertEqual(foo.run('John/xyz'), "'John',-1")
if __name__ == '__main__':
unittest.main()
此单元测试成功。但我认为我的测试方法并不可靠。这个单元测试基本上是一个hack,因为我不知道如何正确地测试回调是否使用正确类型的参数调用。我觉得奇怪的是,AppTest的f
方法通过尝试返回一个由参数的repr()
组成的值来分担类型检查的责任,至少可以说,这个方法并不健壮
你能帮帮我吗?是否可以免除f
方法测试类型的责任?编辑:
尝试使用(Python 3.3上的标准库)。它允许您断言如何调用方法。例如:
import unittest
from unittest.mock import Mock
from app import Foo
class AppTest(unittest.TestCase):
def test_callback(self):
foo = Foo()
f = Mock()
foo.set_handler(f)
foo.run('John/20')
f.assert_called_with('John', 20)
foo.run('John/xyz')
f.assert_called_with('John', -1)
if __name__ == '__main__':
unittest.main()
我添加了另一个更符合您描述的解决方案。谢谢!这正是我想要的东西。