假设我有一个简单的类对象,它看起来像某种Counter
(当然它还有其他函数,但它超出了这个问题的范围):
from collections import Counter
class Vocabulary:
def __init__(self, words):
self.vocab = Counter(words)
将Vocabulary
类添加到unittest中,我可以使用setUpClass
类方法:
或者我可以使用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)
以上两种方法都可以。但如果我有一种不和谐的模式呢:
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
的unittest的第三个版本与前两个惯用测试之间有什么区别吗?在
对于
unittest.TestCase
子类,不要在__init__
中进行任何测试设置。不是为了这个。如果希望每次测试都执行一次设置,请将其放在此处:如果要在每个测试类中执行一次安装程序,请将其放在此处:
^{pr2}$最后让我们解决一个误解。这两者在技术上没有区别:
^{pr2}$还有这个:
第二种方法只是用一种更令人困惑/更糟糕的方式来写第一种。在
相关问题 更多 >
编程相关推荐