在编写一些测试应该引发而另一些测试不应该引发的表驱动测试时,如何避免在两个不同的位置调用正在测试的函数?
这就是我想要做的,但它未能通过None
比assertRaises
:
tests = [
(0, None),
(1, None),
(-1, TooFewException),
(99, None),
(100, TooManyException),
]
for n, exc in tests:
with self.assertRaises(exc):
results = my_code(n)
assert len(results) == n
我想出的最好的办法就是这样,但多余的my_code
电话让我感到不安:
tests = [
(0, None),
(1, None),
(-1, TooFewException),
(99, None),
(100, TooManyException),
]
for n, exc in tests:
if exc is not None:
with self.assertRaises(exc):
my_code(n)
else:
results = my_code(n)
assert len(results) == n
在使用@AmuroRay的答案在我们的基本测试用例上添加助手函数之后,现在是:
tests = [
(0, None),
(1, None),
(-1, TooFewException),
(99, None),
(100, TooManyException),
]
for n, exc in tests:
with self.assertRaisesUnlessNone(exc):
results = my_code(n)
assert len(results) == n