0
0

More than 3 years have passed since last update.

【python】【pytest-mock】クラス外メソッドをモックにする方法

Posted at

クラス外メソッドをモックにする必要があった為、その方法のメモ書き。
例として、以下の「time_util.py」があったとします。

time_util.py
import time
def time_msec() -> int:
    return int(time.time() * 1000)

「time_util.py」は、pyファイルに直にメソッドが記載されているもので、
これをpytest-mockを利用して、モック化する場合に、以下の記述でモック化する事が出来ませんでした。

test01.py(修正前)
import time_util
class Test正常系():
    def test_正常ケース(self, mocker):
        # time_msecをモックにする
        mock_test = mocker.patch("time_util.time_msec")
        mock_test.return_value = 1000

上記の形で実行してもコード上は実行時エラーとならず進みますが、実際にはモック化出来ておりません。
方法として、「time_util.py」をimportしている個所(※ここでは仮に、xxx_class.pyで使用しているとする)をモック化します。

test01.py(修正後)
import time_util
import xxx_class
class Test正常系():
    def test_正常ケース(self, mocker):
        # time_msecをモックにする
        mock_test = mocker.patch("xxx_class.time_util.time_msec")
        mock_test.return_value = 1000

上記のような形で、うまくモック化する事が出来ました。

※まぁそもそもpyファイル内で、クラス化していないのもどうかと思うが。。
 解決した方法のメモ書き程度にとらえて頂ければ幸いです。

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