如何模拟对象方法的返回值

时间:2019-06-26 12:01:05

标签: python unit-testing mocking pytest python-mock

我目前拥有的是:

def some_method():
    some_obj = some_other_method()
    # This is what I want to mock return value of:
    some_obj.some_obj_some_method()

@patch('some_package.some_other_method')
def test_some_stuff(some_other_method_patch):
    some_other_method_patch.return_value = SomeObject()

如何获得将some_obj.some_obj_some_method()返回值设置为False的信息?

2 个答案:

答案 0 :(得分:1)

您可以使用patch.object

import mock
import some_obj
@mock.patch.object(some_obj, "some_obj_some_method")
def test_some_stuff(mock_some_obj_some_method):
    mock_some_obj_some_method.return_value = False

答案 1 :(得分:1)

patch('some_package.some_other_method')将功能some_other_method替换为Mock。现在,您需要替换此模拟方法的方法some_obj_some_method的返回值:

mock.return_value.some_obj_some_method.return_value = False

完整的示例:

# some_package.py

class SomeObject:
    def some_obj_some_method(self):
        raise RuntimeError()


def some_other_method():
    return SomeObject()


def some_method():
    some_obj = some_other_method()
    # This is what you want to mock return value of:
    return some_obj.some_obj_some_method()

测试:

from unittest.mock import patch
from some_package import SomeObject, some_method

@patch('some_package.some_other_method')
def test_some_stuff(function_mock):
    function_mock.return_value.some_obj_some_method.return_value = False
    assert not some_method()

测试将按原样通过,将产生RuntimeError而不会打补丁,并且在断言时会在没有行function_mock.return_value.some_obj_some_method.return_value = False的情况下失败,因为some_method将仅返回一个{ Mock