Skip to main content
 首页 » 编程设计

Python assertRaises 处理用户定义的异常

2025年05月04日11虾米哥

以下问题是由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 上运行单元测试时,为什么引发用户定义异常 (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) 

请您参考如下方法:

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

import unittest 
from foobar import MyException 
import foobar as fb 
 
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() 

这段代码现在应该可以工作了

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