LoginSignup
0
0

[pytest-mock]インスタンス変数をmock化したい

Last updated at Posted at 2023-03-27

自分が詰まった点を備忘として残します。
ひとまず現時点での解決したやり方

テスト対象のインスタンス変数

こちらは調べたらすぐ出てくる

class Target:
    def __init__(self):
        self.value = 100

def test_1(mocker):
    target = Target()
    mocker.patch.object(target, "value", 0)

テスト対象ではないクラスのインスタンス変数

こっちが詰まった

hoge.py
class Hoge:
    def __init__(self):
        self.value = 100
target.py
from hoge import Hoge

def func():
    hoge = Hoge()
    hoge_value = hoge.value

target.pyのhoge.valueをmockにしたい

ダミーのクラスを定義する

target_test.py
class HogeMock:
    def __init__(self):
        self.value = 0

def test_1(mocker):
    mocker.patch("target.Hoge", new=HogeMock)

HogeMockとして定義する。項目が多い、再利用したいなどにも使える。

ただしHogeクラスに他のメソッドが存在する場合はHogeMockにも記載する必要がある。
Hogeにgetというメソッドがあった場合、クラスをmock化していない場合は以下で実行できるが、
mock化しているとgetが存在しない、とエラーになる。

    mocker.patch("target.Hoge.get", return_value=200)

その場合はHogeMockにもgetメソッドを追加する必要がある。

target_test.py
class HogeMock:
    def __init__(self):
        self.value = 0

    def get(self):
        pass

def test_1(mocker):
    mocker.patch("target.Hoge", new=HogeMock)

テスト共通にしたい場合、以下

変更したいからmockにしているけれど。

@pytest.fixture(autouse=True)
def init_mock(mocker):
    mocker.patch("target.Hoge", new=HogeMock)

def test_1():
    ...

参考

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