简体   繁体   English

如何模拟对象方法返回值

[英]How to mock objects methods return value

what I currently have is: 我现在拥有的是:

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()

How could I get about setting some_obj.some_obj_some_method() return value to False? 我怎样才能将some_obj.some_obj_some_method()返回值设置为False?

You can use patch.object 您可以使用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

patch('some_package.some_other_method') will replace the function some_other_method with a Mock . patch('some_package.some_other_method')将使用Mock替换some_other_method函数。 Now you need to replace the return value of the method some_obj_some_method of this mock: 现在你需要替换这个mock的方法some_obj_some_method的返回值:

mock.return_value.some_obj_some_method.return_value = False

The complete example: 完整的例子:

# 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()

Test: 测试:

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()

The test will pass as is, will raise a RuntimeError without patching and fail the assertion without the line function_mock.return_value.some_obj_some_method.return_value = False because some_method will only return a Mock that is never False . 测试将按原样传递,将在没有修补的情况下引发RuntimeError并且在没有行function_mock.return_value.some_obj_some_method.return_value = False的情况下使断言失败,因为some_method将仅返回永远不为FalseMock

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM