本文介绍了python单元测试中的assertRaises没有捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我为什么下面的单元测试失败了吗?test_bad中的ValueError,而不是用assertRaises捕获并成功吗?我认为我使用的是正确的程序和语法,但是ValueError没有被捕获.

Can somebody tell me why the following unit-test is failing on theValueError in test_bad, rather than catching it with assertRaisesand succeeding? I think I'm using the correct procedure and syntax,but the ValueError is not getting caught.

我在Linux机器上使用的是Python 2.7.5.

I'm using Python 2.7.5 on a linux box.

这是代码...

import unittest

class IsOne(object):
    def __init__(self):
        pass
    def is_one(self, i):
        if (i != 1):
            raise ValueError

class IsOne_test(unittest.TestCase):

    def setUp(self):
        self.isone = IsOne()

    def test_good(self):
        self.isone.is_one(1)
        self.assertTrue(True)

    def test_bad(self):
        self.assertRaises(ValueError, self.isone.is_one(2))

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

这是单元测试的输出:

======================================================================
ERROR: test_bad (__main__.IsOne_test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test/raises.py", line 20, in test_bad
    self.assertRaises(ValueError, self.isone.is_one(2))
  File "test/raises.py", line 8, in is_one
    raise ValueError
ValueError

----------------------------------------------------------------------
Ran 2 tests in 0.008s

FAILED (errors=1)

推荐答案

Unittest的 assertRaises 带有一个callable和arguments,因此在您的情况下,您可以这样称呼它:

Unittest's assertRaises takes a callable and arguments, so in your case, you'd call it like:

self.assertRaises(ValueError, self.isone.is_one, 2)

如果愿意,从Python2.7开始,您还可以将其用作上下文管理器,例如:

If you prefer, as of Python2.7, you could also use it as a context manager like:

with self.assertRaises(ValueError):
    self.isone.is_one(2)

这篇关于python单元测试中的assertRaises没有捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 11:47