2016-04-08 97 views
1

每個單元測試之前調用這是我的代碼,測試類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

是什麼'assertItemsEqual'使_db實例屬性? –

+0

'self.school'確實創建了 – user3159253

+0

你如何運行測試?你在問題中粘貼了_exact_輸出嗎? – snakecharmerb

回答

2

的問題是,School._db是的類的屬性,而不是上實例,所以修改School._db測試運行之間的生存。

你應該初始化它School.__ init __

class School(): 

    def __init__(self, name): 
     self.name = name 
     self._db = dict() 
+0

!非常感謝你! –