2014-04-03 49 views
1

我要趕在代碼生成一個類型錯誤,但不幸的是,單元測試失敗:如何捕捉「類型錯誤」與assertRaises()

下面是代碼:

import unittest                 

class _Foo(object):                
    def __init__(self):               
     self.bar = ['AAA']              

    def _validate_bar(self, bar):            
     if not isinstance(bar, list):           
      raise TypeError              
     return True                

class Foo(_Foo):                 
    def __init__(self, bar=None):            
     super(Foo, self).__init__()            
     if bar and self._validate_bar(bar):          
      self.bar = bar              

class FooTest(unittest.TestCase):            

    def test_bar_as_string(self):            
     self.assertRaises("TypeError", Foo("a"))         

    #def test_a(self):               
    # try:                 
    #  Foo('a')               
    # except Exception as exc:            
    #  self.assertEqual('TypeError', exc.__class__.__name__)    

    #def test_bar_as_string(self):            
    # with self.assertRaises("TypeError"):         
    #  Foo("a")               

if __name__ == "__main__":        

以下是錯誤:

test_bar_as_string (__main__.FooTest) ... ERROR 

====================================================================== 
ERROR: test_bar_as_string (__main__.FooTest) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "test.py", line 21, in test_bar_as_string 
    self.assertRaises("TypeError", Foo("a")) 
    File "test.py", line 15, in __init__ 
    if bar and self._validate_bar(bar): 
    File "test.py", line 9, in _validate_bar 
    raise TypeError 
TypeError 

---------------------------------------------------------------------- 
Ran 1 test in 0.000s 

FAILED (errors=1) 



    unittest.main(verbosity=2) 

回答

7

引文結束的TypeError,不直接調用Foo,但傳遞函數(類Foo)和參數。

def test_bar_as_string(self):            
    self.assertRaises(TypeError, Foo, "a") 

或者,你可以使用assertRaises爲上下文管理器:

def test_bar_as_string(self):            
    with self.assertRaises(TypeError): 
     Foo("a")         
+0

看你的例子後,我意識到,我在'TypeError'周圍放了''''這就是爲什麼我的註釋代碼不起作用。 – Vor

2

你會做得一樣:

with self.assertRaises(TypeError): 
    Foo("a") 

self.assertRaises(TypeError, Foo, "a")