Python unittest 以失败告终
Python unittest ends with failure
我运行下面的单元测试在python,结果应该是正确的,但是单元测试出错了
哪里出错了?
这是我要测试的Class
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())
这是 put
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()
Exception
对象不实现自定义相等性测试,没有 __eq__
方法只有 身份测试 会是真的:
>>> a = ValueError()
>>> a == a
True
>>> a == ValueError()
False
您根本不需要测试相等性 ,因为 self.assertRaises
只会捕获一个 ValueError
实例 无论如何.
如果您确实有不同的原因来测试异常是 ValueError
,请改用 isinstance()
:
self.assertTrue(isinstance(cm.exception, ValueError))
否则,cm.exception
仅用于测试异常的其他 方面,如特定属性。
我运行下面的单元测试在python,结果应该是正确的,但是单元测试出错了
哪里出错了?
这是我要测试的Class
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())
这是 put
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()
Exception
对象不实现自定义相等性测试,没有 __eq__
方法只有 身份测试 会是真的:
>>> a = ValueError()
>>> a == a
True
>>> a == ValueError()
False
您根本不需要测试相等性 ,因为 self.assertRaises
只会捕获一个 ValueError
实例 无论如何.
如果您确实有不同的原因来测试异常是 ValueError
,请改用 isinstance()
:
self.assertTrue(isinstance(cm.exception, ValueError))
否则,cm.exception
仅用于测试异常的其他 方面,如特定属性。