Python assertRaises用户定义的异常

时间:2016-02-18 19:36:43

标签: python class exception-handling message-passing assertraises

this post中的讨论触发了以下问题。

假设有两个文件( foobar.py foobar_unittest.py )。文件 foobar.py 包含一个具有两个函数( foo bar )的类( FooBar )。函数 bar 引发内置异常,函数 foo 是用户定义的异常。

# foobar.py
class MyException(Exception):
    pass
class FooBar:
    def __init__(self):
        pass
    def bar(self):
        raise ValueError('Hello World.')
    def foo(self):
        raise MyException('Hello World.')

# foobar_unittest.py
import unittest
import foobar as fb
class MyException(Exception):
    pass
class FooBarTestCases(unittest.TestCase):
    def test_bar(self):
        with self.assertRaises(ValueError):
            fb.FooBar().bar()
    def test_foo(self):
        with self.assertRaises(MyException):
            fb.FooBar().foo()
if __name__ == '__main__':
    unittest.main()

foobar.py 上运行unit-test时,为什么提升用户定义的异常( foo )的函数无法通过测试?

>>> python2.7 foobar_unittest.py 
.E
======================================================================
ERROR: test_foo (__main__.FooBarTestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "foobar_unittest.py", line 11, in test_foo
    fb.FooBar().foo()
  File "/a_path/foobar.py", line 9, in foo
    raise MyException('Hello World.')
MyException: Hello World.

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=1)

1 个答案:

答案 0 :(得分:0)

从foobar导入MyException,不要重新定义它。

..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

此代码现在可以用作

{{1}}
相关问题