我对单元测试相当陌生,并且正在尝试找出该事物的最佳实践。我在这里看到了几个与单元测试继承一个本身包含多个测试的基类有关的问题,例如:
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
看来这可以为我在所有其他测试上节省大量时间:
另一个_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
注意:这是基于我在谷歌应用引擎上的 webapp2 中的一些工作,但我预计几乎所有 python web 应用程序都会出现类似的情况
我的问题
使用包含所有其他测试继承的有用方法/变量的基类/辅助类是一种好习惯,还是每个测试类都应该是“自包含的”?
谢谢!