我有一组测试用例,它们都应该完成完全相同的测试,按照“方法 x 是否返回现有文件的名称?”
我认为最好的方法是从它们共享的 TestCase 派生一个基类,然后简单地将测试添加到该类。不幸的是,测试框架仍然尝试为基类运行测试,这没有意义。
class SharedTest(TestCase):
def x(self):
...do test...
class OneTestCase(SharedTest):
...my tests are performed, and 'SharedTest.x()'...
如果它是在基类的对象而不是像这样的派生类上调用的,我试图破解一个检查以简单地跳过测试:
class SharedTest(TestCase):
def x(self):
if type(self) != type(SharedTest()):
...do test...
else:
pass
但是出现了这个错误:
ValueError: no such test method in <class 'tests.SharedTest'>: runTest
首先,我想要任何关于执行此操作的优雅建议。其次,虽然我真的不想使用 type() hack,但我想了解为什么它不起作用。
最佳答案
您可以通过利用测试运行器仅运行继承自 unittest.TestCase
(Django 的 TestCase
继承自。)的测试来使用混合。例如:
class SharedTestMixin(object):
# This class will not be executed by the test runner (it inherits from object, not unittest.TestCase.
# If it did, assertEquals would fail , as it is not a method that exists in `object`
def test_common(self):
self.assertEquals(1, 1)
class TestOne(TestCase, SharedTestMixin):
def test_something(self):
pass
# test_common is also run
class TestTwo(TestCase, SharedTestMixin):
def test_another_thing(self):
pass
# test_common is also run
有关为什么这有效的更多信息,请搜索 python 方法解析顺序和多重继承。
关于python - 如何将测试方法添加到一组 Django TestCase 派生类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3605936/