使用Python的内置单元测试时,至少有2种不同的方式来组织班级设置,使用setUpClass()
或仅使用老式的班级成员。什么时候使用,什么时候使用?
class TestFoo(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.foo = Foo(...)
def test_blah(self):
self.foo.do_something()
...
VS
class TestFoo(unittest.TestCase):
foo = Foo(...)
def test_blah(self):
self.foo.do_something()
...
答案 0 :(得分:-1)
实际上,除了您要使用@skipUnless(condition)
装饰器之外,上述问题中的2个代码段基本上相同。
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
VS
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