首页 > 解决方案 > 我什么时候应该使用 setUpClass 什么时候只使用一个类成员?

问题描述

当使用 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()
        ...

标签: pythonpython-unittest

解决方案


事实上,上述问题中的 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

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

推荐阅读