我对单元测试比较新,正在尝试了解最佳实践。我在这里看到过一些关于单元测试继承基类的问题,该基类本身包含多个测试,例如:
class TestBase(unittest.TestCase):
# some standard tests
class AnotherTest(TestBase):
# run some more tests in addition to the standard tests
我认为从社区中得到的建议是,最好为每个实现编写单独的测试并使用多重继承。但是,如果基类实际上不包含任何测试-只是所有其他测试的辅助工具呢?例如,假设我有一个基本测试类,我用它来存储大多数甚至所有其他测试将使用的一些常见方法。让我们还假设我在
models.py
中有一个名为ContentModel
的数据库模型。
test_base.py
import webtest
from google.appengine.ext import testbed
from models import ContentModel
class TestBase(unittest.TestCase):
def setUp(self):
self.ContentModel = ContentModel
self.testbed = testbed.Testbed()
self.testbed.activate()
# other useful stuff
def tearDown(self):
self.testbed.deactivate()
def createUser(self, admin=False):
# create a user that may or may not be an admin
# possibly other useful things
看起来这将在所有其他测试中节省我大量时间:
another_test.py
from test_base import TestBase
class AnotherTest(TestBase):
def test_something_authorized(self):
self.createUser(admin=True)
# run a test
def test_something_unauthorized(self):
self.createUser(admin=False)
# run a test
def test_some_interaction_with_the_content_model(self):
new_instance = self.ContentModel('foo' = 'bar').put()
# run a test
注意:这是基于我在Google App Engine上的Webapp2工作的一些内容,但我预计几乎任何Python Web应用程序都会出现类似的情况。
我的问题
使用包含有用方法/变量的基础/助手类,让所有其他测试继承它,这样做是否是一个好的实践,还是每个测试类应该是“自包含”的?
谢谢!