python - 我什么时候应该使用 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()
...
解决方案
事实上,上述问题中的 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
推荐阅读
- azure - 尝试从 azure VM 连接到 cosmosDB 时连接超时
- ios - 表情符号不显示在推送通知中
- java - Java gc - 什么是长寿对象?
- actions-on-google - 是否可以创建一个 Home 控件操作来控制非 Android 电视?
- vba - 不同初始化的用户表单加载
- jquery - TypeError: jQuery 是未定义的 WordPress
- html - 为我的引导导航栏上的活动链接添加背景颜色
- c# - 如何在 C# 中为 Google 语音识别 api 准备音频文件(wav 或 mp3)?
- java - java.lang.ClassNotFoundException:org.jooq.util.JavaGenerator
- angular - Angular 不会导入显示错误的 Rxjs