【发布时间】:2016-12-27 23:50:45
【问题描述】:
考虑以下几点:
import unittest
class MyClass:
def __init__(self, dict: {}):
try:
if self.validate_dict(dict):
self.data = dict
except Exception as e:
raise Exception('Unable to create MyClass: {}'.format(str(e)))
def validate_dict(self, dict: {}):
if 'special_key' not in dict:
raise Exception('Missing Key: special_key')
# ... perhaps more complicated validation code...
return True
class MyTests(unittest.TestCase):
def test_bad_validation(self):
with self.assertRaises(Exception) as context:
test_dict = {}
test_class = MyClass(test_dict)
self.assertTrue('Unable to create' in str(context.exception))
...假设这不是对这个函数进行单元测试的糟糕方法,除了 {} 之外,我如何向单元测试添加更多测试用例?
我觉得一目了然地查看特定测试的所有测试用例的漂亮列表并快速添加新测试用例会很有用。
我找到了一个库 DDT 来解决这个问题,但似乎没有任何方法可以将整个对象(如 dict)作为测试参数传递而无需解包。在这种情况下,我想测试是否存在密钥(可能有很多),因此将它们解压缩到像 DDT 这样的单独争论中似乎是一个糟糕的解决方案。
unittest 是否支持这样的事情?我知道pytest 可以,但我想先看看unittest 有什么可能。
还可以通过其他方法对此代码进行单元测试。
【问题讨论】:
标签: python unit-testing data-driven-tests data-driven