assertpythonraise_Python assertRaise在用户定义的异常上引发

The following question was triggered by the discussion in this post.

Assume two files (foobar.py and foobar_unittest.py). File foobar.py contains a class (FooBar) with two functions (foo and bar). Function bar raises a built-in exception, function foo a user-defined exception.

# 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()

When running unit-test on foobar.py, why does the function raising the user-defined exception (foo) fail to pass the test?

>>> 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)

解决方案

import MyException from foobar, don't redefine it.

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()

This code should work now as

..

----------------------------------------------------------------------

Ran 2 tests in 0.001s

OK

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值