我对 Python 比较陌生。根据unittest.setUp文档:
setUp()
Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.
我关于setUp
的问题如下:
在我们的测试代码库中,我看到我们通过继承unittest.TestCase
来自定义Python测试框架。最初,unittest.TestCase
的名称为 setUp
和 tearDown
。在自定义类中,我们有 setUpTestCase
和 拆解测试用例
。所以每次都会调用这两个函数,而不是原来的对应函数。
我的问题是:
- 底层测试运行器如何调用这些
setUp
和tearDown
函数? - 是否要求那些用于设置测试用例的函数应以
setUp
开头,用于拆除测试用例的函数应以tearDown
开头?或者它可以命名为任何有效的标识符?
谢谢。
最佳答案
- setUp() 和 tearDown() 方法在继承自 unittest.TestCase 的类中可用时会自动使用。
- 它们应该命名为 setUp() 和 tearDown(),只有在执行测试方法时才会使用它们。
例子:
class MyTestCase(unittest.TestCase):
def setUp(self):
self.setUpMyStuff()
def tearDown(self):
self.tearDownMyStuff()
class TestSpam(MyTestCase):
def setUpMyStuff(self):
# called before execution of every method named test_...
self.cnx = # ... connect to database
def tearDownMyStuff(self):
# called after execution of every method named test_...
self.cnx.close()
def test_get_data(self):
cur = self.cnx.cursor()
...
关于Python 单元测试设置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657543/