单元测试断言引发异常

时间:2011-08-19 03:06:34

标签: python unit-testing assertions python-unittest

当我在测试两个整数相等的单元测试时,我得到一个断言错误异常,而不是单元测试报告失败,然后进行下一个测试。这是测试代码(大大简化以证明这一点)。

import unittest

class TestClass(unittest.TestCase):

    def test_method(self):
        myVariable = 1
        self.assertTrue(myVariable==0)

if __name__ == '__main__':
    unittest.main()

回溯如下:

builtins.AssertionError: False is not true
File "C:\Dev\Volleyball\test.py", line 10, in <module>
  unittest.main()
File "C:\Program Files\python32\Lib\unittest\main.py", line 124, in __init__
  self.runTests()
File "C:\Program Files\python32\Lib\unittest\main.py", line 270, in runTests
  self.result = testRunner.run(self.test)
File "C:\Program Files\python32\Lib\unittest\runner.py", line 168, in run
  test(result)
File "C:\Program Files\python32\Lib\unittest\suite.py", line 67, in __call__
  return self.run(*args, **kwds)
File "C:\Program Files\python32\Lib\unittest\suite.py", line 105, in run
  test(result)
File "C:\Program Files\python32\Lib\unittest\suite.py", line 67, in __call__
  return self.run(*args, **kwds)
File "C:\Program Files\python32\Lib\unittest\suite.py", line 105, in run
  test(result)
File "C:\Program Files\python32\Lib\unittest\case.py", line 498, in __call__
  return self.run(*args, **kwds)
File "C:\Program Files\python32\Lib\unittest\case.py", line 446, in run
  self._executeTestPart(testMethod, outcome, isTest=True)
File "C:\Program Files\python32\Lib\unittest\case.py", line 391, in _executeTestPart
  function()
File "C:\Dev\Volleyball\test.py", line 7, in test_method
  self.assertTrue(myVariable==0)
File "C:\Program Files\python32\Lib\unittest\case.py", line 527, in assertTrue
  raise self.failureException(msg)

我做错了什么,或者我误解了测试断言是如何工作的?

为了记录,我在Windows 7上使用Python 3.2.1。

TIA,艾伦

2 个答案:

答案 0 :(得分:0)

对 - 感谢@agf我达成了可接受的妥协。我已经从'Debugger:Exceptions'的'Always Report'部分删除了AssertionError,现在调试器不再停止在断言上。缺点是虽然在运行测试脚本时这很好(因为我会在失败列表中看到结果),但在运行'真正'程序时我将不得不关注'调试I / O' 输出以查看断言。

感谢所有回复的人。

艾伦

答案 1 :(得分:0)

而不是self.assertTrue(myVariable == 0)尝试使用self.assertEqual(myVariable,0)