当使用 Python 的内置单元测试时,至少有 2 种不同的方法来组织类级设置,使用 setUpClass()
或只使用老式类成员。何时使用一个,何时使用另一个?
class TestFoo(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.foo = Foo(...)
def test_blah(self):
self.foo.do_something()
...
对比
class TestFoo(unittest.TestCase):
foo = Foo(...)
def test_blah(self):
self.foo.do_something()
...
最佳答案
事实上,上述问题中的 2 个代码片段的工作原理基本相同,除非您要使用 @skipUnless(condition)
装饰器。
SETTINGS = json.load(...)
@unittest.skipUnless("foo" in SETTINGS, "skipped")
class TestFoo(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.foo = Foo(SETTINGS["foo"])
# If SETTINGS["foo"] is undefined,
# this entire test class would be skipped
对比
SETTINGS = json.load(...)
@unittest.skipUnless("foo" in SETTINGS, "skipped")
class TestFoo(unittest.TestCase):
foo = Foo(SETTINGS["foo"])
# This line will always be executed,
# BEFORE the skipUnless(...),
# so if SETTINGS["foo"] is undefined,
# there will be a runtime error here
关于python - 什么时候应该使用 setUpClass 什么时候只使用类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52474130/