2017-04-02 71 views
0

我在python中運行以下單元測試,結果應該是正確的,但單元測試出錯了。Python單元測試以失敗告終

什麼是錯誤?

這是類考試我一定要

class Strategy: 
    _a = 0 
    _b = 0 
    _result = 0 

    def __init__(self, a, b): 

     try: 
      int(a) 
      int(b) 
     except ValueError: 
      raise ValueError() 

     self._a = a 
     self._b = b 

這是我的單元測試

def test_invalideValue(self): 
    with self.assertRaises(ValueError) as cm: 
     StrategyAddition('A', 3) 

    self.assertEqual(cm.exception, ValueError()) 

這看跌

Failure 
Traceback (most recent call last): 
    File "C:\Users\Michi\workspace_python\DesignPatternPython\Strategy\TestStrategy.py", line 24, in test_invalideValue 
    self.assertEqual(cm.exception, ValueError()) 
AssertionError: ValueError() != ValueError() 

回答

5

Exception對象不實現自定義相等測試,並且沒有__eq__方法身份測試小號將是真實的:

>>> a = ValueError() 
>>> a == a 
True 
>>> a == ValueError() 
False 

你並不需要在所有測試相等,因爲self.assertRaises只會趕上ValueError實例反正

如果你確實有不同的原因,以測試的例外是ValueError,使用isinstance()代替:

self.assertTrue(isinstance(cm.exception, ValueError)) 

否則,cm.exception只存在測試異常其他方面,如特定屬性。