0
0

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 1 year has passed since last update.

mocker.spyの使い方、使い所

Last updated at Posted at 2023-08-04

mockとは

  • mockとは依存する関数やクラスが正しく使われているかどうかをテストする時に使われるオブジェクト
  • mockerを用いると指定した対象を偽の実装にすり替えて、引数や呼び出し回数を保存できるオブジェクト(すなわちモック)にすることができる。

moker.spyとは

  • 指定した対象の本物のメソッドを呼びつつ呼び出し回数を確認や引数、返り値を確認できる。

使い所

テスト実行時に

  • コントローラからjobのテストをしたい時
  • 外部システムへアクセスする際

使い方

指定した対象をmock化し後続でtestしたいものをcallする
Spyより

methodをテストする場合

def test_spy_method(mocker):
    class Foo(object):
        def bar(self, v):
            return v * 2

    foo = Foo()
    spy = mocker.spy(foo, 'bar')
    assert foo.bar(21) == 42

    spy.assert_called_once_with(21)
    assert spy.spy_return == 42

funcitonをテストする場合

def test_spy_function(mocker):
    # mymodule declares `myfunction` which just returns 42
    import mymodule

    spy = mocker.spy(mymodule, "myfunction")
    assert mymodule.myfunction() == 42
    assert spy.call_count == 1
    assert spy.spy_return == 42
  • spyの返すオブジェクト
    • 基本的にはmockと同じものが使えるが加えて2つ追加されている。
    • spy_return: spyされた戻り値
    • spy_exception: spyされた関数/メソッドが最後に呼び出されたときに発生した例外の値。
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?