如何设置多个单元测试共享的资源? [英] How to set up a resource shared by several unit tests?
本文介绍了如何设置多个单元测试共享的资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 中,如何为一整套单元测试设置一个设置(可能包含昂贵的函数调用)?
In Python, how can I have one setup (which may contain expensive function calls) for a whole set of unit tests?
示例:
import unittest
class Test1(unittest.TestCase):
def setUp(self):
print "expensive call"
def test1(self):
self.assertEqual(1, 1)
def test2(self):
self.assertEqual(1, 1)
if __name__ == "__main__":
unittest.main()
将运行两次昂贵的调用:
Will run the expensive call twice:
$ python unittest.py
expensive call
.expensive call
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
如何更改它以便只进行一次昂贵的调用并且所有测试都可以访问其资源?
How can I change it so the expensive call is made only once and its resources accessible to all tests?
更新:我使用的是 Python 2.6.
UPDATE: I'm using Python 2.6.
推荐答案
可以使用 setUpClass
You can use setUpClass
import unittest
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
print 'setUpClass'
cls.data = 123
def test_one(self):
print 'test_one'
print self.data
def test_two(self):
print 'test_two'
if __name__ == "__main__":
unittest.main()
参见 http://docs.python.org/library/unittest.html#unittest.TestCase.setUpClass
更新:
对于 python 2.6,我想你可以使用类级属性:
For python 2.6, I suppose you could use class-level attributes:
class Test(unittest.TestCase):
value = result_of_some_expensive_function()
def test(self):
print self.value
该函数将在您的测试定义后运行一次.
That function will run once when your test is defined.
这篇关于如何设置多个单元测试共享的资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文