我遇到单元测试问题,断言提出我自己的异常。问题是测试总是失败。而且我不知道为什么。这是我的项目文件:
foo
|- __init__.py
|- exceptions.py
|- foo.py
tests
|- __init__.py
|- test_foo.py
exceptions.py
class MyException(Exception):
def __init__(self, msg=None):
if msg is None:
msg = "An error occurred"
super(MyException, self).__init__(msg)
foo.py
from exceptions import *
class Foo:
def bar(self):
raise MyException
test_foo.py
from unittest import TestCase
from foo.foo import Foo
from foo.exceptions import MyException
class TestFoo(TestCase):
def setUp(self):
self.foo = Foo()
def test_bar(self):
with self.assertRaises(MyException):
self.foo.bar()
当我运行测试时,它失败并且脚本在控制台中输出:
Error
Traceback (most recent call last):
File "...\lib\unittest\case.py", line 59, in testPartExecutor
yield
File "...\lib\unittest\case.py", line 605, in run
testMethod()
File "...\tests\test_foo.py", line 14, in test_bar
self.foo.bar()
File "...\foo\foo.py", line 8, in bar
raise MyException
exceptions.MyException: An error occurred
Ran 1 test in 0.002s
FAILED (errors=1)
当我在第13行的测试中将MyException更改为Exception时,它可以正常工作。但我想测试它的具体例外情况。知道为什么这不起作用吗?
答案 0 :(得分:0)
我通过更改
修复了它from exceptions import *
到
from foo.exceptions import *
在foo.py文件中。