2017-04-02 76 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只存在测试异常其他方面,如特定属性。