14
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Python] Exceptionをraiseするモック関数の作り方

Posted at

ある関数が例外を発生した時に意図した挙動になるかなどテストしたい場合があります。
side_effectという属性を使って簡単に実現できます。

mock = Mock()
mock.side_effect = Exception("Mock Exception")

# または
mock = Mock(side_effect=Exception("MockException")

テスト関数にパッチを適用すると、モックの戻しが必要なくて楽ちん

@patch("some_function", MagicMock(side_effect=Exception()))
def test_hoge_raise_exception_from_some_function(self): 
    pass # なんかテストする

参考

14
10
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
14
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?