2017-10-17 69 views
0

我正在運行一個小的unittest來檢查羅馬數字轉換器。這裏是我的代碼: -self.assertTrue在Python 3.x中拋出追溯錯誤unittesting

class RomConverter(object): 
    def __init__(self): 
     self.digital_mapping = {"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1} 
    def convert(self, rom_num): 
     value = 0  
     for char in rom_num: 
      val += self.digital_mapping[char] 
      return value 

import unittest 
class RomConverterTest(unittest.TestCase): 
    def settingUp(self): 
     print ("Creating a new RomConverter...") 
     self.cvt = RomConverter() 
    def tearDown(self): 
     print ("Destroying the RomConverter...") 
     self.cvt = None 
    def test_empty_num(self): 
     self.assertTrue(self.cvt.convert("") == 0) 
     self.assertFalse(self.cvt.convert("") > 0) 
    def test_no_rom_num(self): 
     self.assertRaises(TypeError,self.cvt.convert, None) 
if __name__ == "__main__": 
    unittest.main() 

但是當我運行的代碼我得到這個消息: -

Traceback (most recent call last): 
    File "receipe2 - Copy.py", line 31, in test_empty_roman_numeral 
    self.assertTrue(self.cvt.convert_to_decimal("") == 0) 
AssertionError: False is not true 
+0

您發佈的錯誤不是來自您發佈的代碼。 'self.assertTrue(self.cvt.convert_to_decimal(「」)== 0)'在您的代碼中未提及。 –

回答

1

我看到你的代碼的兩個問題。

首先def settingUp(self):應該def setUp(self):

def convert(self, rom_num):回縮進得多。結果該方法不返回空白字符串0。 這是一個工作版本:

class RomConverter(object): 
    def __init__(self): 
     self.digital_mapping = {"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1} 
    def convert(self, rom_num): 
     value = 0 
     for char in rom_num: 
      value += self.digital_mapping[char] 
     return value 

import unittest 
class RomConverterTest(unittest.TestCase): 
    def setUp(self): 
     print ("Creating a new RomConverter...") 
     self.cvt = RomConverter() 
    def tearDown(self): 
     print ("Destroying the RomConverter...") 
     self.cvt = None 
    def test_empty_num(self): 
     self.assertTrue(self.cvt.convert("") == 0) 
     self.assertFalse(self.cvt.convert("") > 0) 
    def test_no_rom_num(self): 
     self.assertRaises(TypeError,self.cvt.convert, None) 

if __name__ == "__main__": 
    unittest.main() 
+0

是的,我想通了。謝謝您的幫助。 –