我有一个如下所示的应用程序代码。
# 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_handler
方法来设置回调。稍后必须使用两个参数调用回调:一个字符串和一个整数。我试图在单元测试中确保这一点。
# 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()
本次单元测试成功。但我不认为我的测试方法是可靠的。这个单元测试基本上是一个黑客,因为我不知道如何正确测试是否使用正确类型的参数调用了回调。我觉得奇怪的是 AppTest 的f
方法通过尝试返回由以下内容组成的值来分担类型检查的责任repr()
论点,至少可以说,这根本不可靠。
请你帮助我好吗?是否可以缓解f
测试责任的方法有哪些类型?