117

テストしようとしている別の関数内で呼び出された関数の戻り値をモックすることは可能ですか? モックされたメソッド (テスト中の多くのメソッドで呼び出される) が呼び出されるたびに、指定した変数を返すようにしたいと考えています。例えば:

class Foo:
    def method_1():
       results = uses_some_other_method()
    def method_n():
       results = uses_some_other_method()

単体テストでは、モックを使用して の戻り値を変更し、uses_some_other_method()で呼び出されるたびに でFoo定義した値を返すようにしたいと考えています。@patch.object(...)

4

4 に答える 4

34

これは、次のような方法で実行できます。

# foo.py
class Foo:
    def method_1():
        results = uses_some_other_method()


# testing.py
from mock import patch

@patch('Foo.uses_some_other_method', return_value="specific_value"):
def test_some_other_method(mock_some_other_method):
    foo = Foo()
    the_value = foo.method_1()
    assert the_value == "specific_value"

ここにあなたが読むことができるソースがあります: Patching in the wrong place

于 2013-08-19T01:28:44.437 に答える
11

あなたが話していることを明確にしましょう:Foo外部メソッドを呼び出すテストケースでテストしたいのですuses_some_other_method。実際のメソッドを呼び出す代わりに、戻り値をモックします。

class Foo:
    def method_1():
       results = uses_some_other_method()
    def method_n():
       results = uses_some_other_method()

上記のコードが にfoo.pyありuses_some_other_method、 module で定義されているとしますbar.py。単体テストは次のとおりです。

import unittest
import mock

from foo import Foo


class TestFoo(unittest.TestCase):

    def setup(self):
        self.foo = Foo()

    @mock.patch('foo.uses_some_other_method')
    def test_method_1(self, mock_method):
        mock_method.return_value = 3
        self.foo.method_1(*args, **kwargs)

        mock_method.assert_called_with(*args, **kwargs)

異なる引数を渡すたびに戻り値を変更したい場合は、mockを提供しますside_effect

于 2015-05-28T09:37:37.410 に答える