python怎么返回进行修改_使用python的mock patch.object更改在另一个方法中调用的方法的返回值...

有两种方法可以做到这一点:使用patch和patch.object

Patch假设您没有直接导入对象,但是您正在测试的对象正在使用它,如下所示#foo.py

def some_fn():

return 'some_fn'

class Foo(object):

def method_1(self):

return some_fn()#bar.py

import foo

class Bar(object):

def method_2(self):

tmp = foo.Foo()

return tmp.method_1()#test_case_1.py

import bar

from mock import patch

@patch('foo.some_fn')

def test_bar(mock_some_fn):

mock_some_fn.return_value = 'test-val-1'

tmp = bar.Bar()

assert tmp.method_2() == 'test-val-1'

mock_some_fn.return_value = 'test-val-2'

assert tmp.method_2() == 'test-val-2'

如果直接导入要测试的模块,可以使用patch.object,如下所示:#test_case_2.py

import foo

from mock import patch

@patch.object(foo, 'some_fn')

def test_foo(test_some_fn):

test_some_fn.return_value = 'test-val-1'

tmp = foo.Foo()

assert tmp.method_1() == 'test-val-1'

test_some_fn.return_value = 'test-val-2'

assert tmp.method_1() == 'test-val-2'

在这两种情况下,在测试功能完成后,某些fn将被“取消模拟”。

编辑:

为了模拟多个函数,只需向函数中添加更多的decorator并添加参数以接受额外的参数@patch.object(foo, 'some_fn')

@patch.object(foo, 'other_fn')

def test_foo(test_other_fn, test_some_fn):

...

注意,decorator离函数定义越近,它在参数列表中的位置就越早。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值