让我们说我有一个简单的类对象,看起来像某种Counter
(当然,它还有其他功能,但超出了此问题的范围):
from collections import Counter
class Vocabulary:
def __init__(self, words):
self.vocab = Counter(words)
然后将Vocabulary
类添加到单元测试中,我本可以这样使用setUpClass
类方法:
import unittest
class VocabularyTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.vocab = Vocabulary(["z", "a", "b", "c", "f", "d", "e", "g", "a", "d", "b", "e", "w"])
def test_counts_set_correctly(self):
self.assertEqual(cls.vocab["a"], 2)
或者我可以只使用self
:
class VocabularyTests(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(VocabularyTests, self).__init__(*args, **kwargs)
self.vocab = Vocabulary(["z", "a", "b", "c", "f", "d", "e", "g", "a", "d", "b", "e", "w"])
def test_counts_set_correctly(self):
self.assertEqual(self.vocab["a"], 2)
以上两种方法都可以正常工作。但是,如果我有一种非Python模式,该怎么办:
import unittest
class VocabularyTests(unittest.TestCase):
@classmethod
def setUpClass(self):
self.vocab = Vocabulary(["z", "a", "b", "c", "f", "d", "e", "g", "a", "d", "b", "e", "w"])
def test_counts_set_correctly(self):
self.assertEqual(self.vocab["a"], 2)
根据What is the 'cls' variable used for in Python classes?,这只是一种编码约定,但是使用@classmethod
的带有self.vocab
的单元测试的第三个版本与前两个惯用测试之间有什么区别?
答案 0 :(得分:2)
对于unittest.TestCase
子类,不要在__init__
中进行任何测试设置。那不是它的目的。如果您希望每次测试方法一次执行一次设置,请放在此处:
def setUp(self):
...
如果您希望每个测试 class 执行一次设置,请放在此处:
@classmethod
def setUpClass(cls):
...
最后,让我们解决一个误解。从技术上讲,两者之间没有区别:
@classmethod
def setUpClass(cls):
...
这:
@classmethod
def setUpClass(self):
...
第二个只是编写第一个的比较混乱/糟糕的方式。