簡體   English   中英

python unittest自己的異常assertRaises

[英]python unittest own exception assertRaises

我在斷言引發我自己的異常的單元測試中遇到問題。 問題是測試總是失敗。 而且我不知道為什么。 這是我的項目文件:

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時,它可以工作。 但是我想測試它的特定異常。 知道為什么這行不通嗎?

我通過更改來修復

from exceptions import *

from foo.exceptions import *

在foo.py文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM