LoginSignup
5
3

More than 5 years have passed since last update.

pythonのunittestでExceptionがraiseされることをテストする方法

Posted at

こんにちはsekitakaです。
いつまでたってもpythonビギナー感が抜けません。

今日はpythonのunittestでExceptionがraise「される」ことをテストする方法を紹介します。

def test_raise_exception(self):
    with self.assertRaises(Exception):
        raise Exception('hogehoge error') # ExceptionのRaiseを期待するテストコード

はじめはtryないでself.fail()して、failが実行される前にexceptに飛ばなければ、テスト成功と判断しようとしたのですが、try内のfailもexceptにキャッチされてしまって、意図したテストになりませんでした。

ダメコード
def test_raise_exception(self):
    try:
        raise Exception('hogehoge error') # ExceptionのRaiseを期待するテストコード
        self.fail("exceptされなかったから失敗")
    except Exception as e:
        pass
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3