这是我测试类School
的代码:
class SchoolTest(unittest.TestCase):
def setUp(self):
# assertCountEqual is py3, py2 only knowns assetItemsEqual
if not hasattr(self, 'assertCountEqual'):
self.assertCountEqual = self.assertItemsEqual
self.school = School("Haleakala Hippy School")
def test_an_empty_school(self):
for n in range(1, 9):
self.assertCountEqual(set(), self.school.grade(n))
def test_add_student(self):
self.school.add("Aimee", 2)
self.assertCountEqual(("Aimee",), self.school.grade(2))
我想在每次测试之前创建一个新的School
对象。当我运行测试时,我最终得到以下错误:
def test_an_empty_school(self):
for n in range(1, 9):
self.assertCountEqual(set(), self.school.grade(n))
AssertionError: Element counts were not equal:
First has 0, Second has 1: 'Aimee'
这意味着首先调用第二个测试并且不创建新对象,这就是第一个测试失败的原因。
如果我评论其中任何一个并运行测试,无论我评论哪一个,它都会通过。
我觉得我错过了一个基本的东西。
我做错了什么?
以防万一,School
类:
class School():
_db = dict()
def __init__(self, name):
self.name = name
@property
def db(self):
return self._db
def add(self, student, grade):
if grade not in self._db:
self._db[grade] = set()
self._db[grade].add(student)
def grade(self, grade):
if grade not in self._db:
return set()
return self._db[grade]
def sort(self):
sorted_list = []
for grade in self._db:
sorted_list.append((grade, tuple(self._db[grade])))
return sorted_list
答案 0 :(得分:3)
问题在于School._db
是类上的属性,而不是实例上的属性,因此对School._db
的修改在测试之间存在运行。
您应该通过初始化School.__ init __
class School():
def __init__(self, name):
self.name = name
self._db = dict()