带有多次调用方法的Python Mock对象 [英] Python Mock object with method called multiple times

查看:336
本文介绍了带有多次调用方法的Python Mock对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在测试的类,该类具有依赖关系的另一个类(该类的实例传递给CUT的init方法).我想使用Python Mock库来模拟此类.

I have a class that I'm testing which has as a dependency another class (an instance of which gets passed to the CUT's init method). I want to mock out this class using the Python Mock library.

我所拥有的是这样的:

mockobj = Mock(spec=MyDependencyClass)
mockobj.methodfromdepclass.return_value = "the value I want the mock to return"
assertTrue(mockobj.methodfromdepclass(42), "the value I want the mock to return")

cutobj = ClassUnderTest(mockobj)

这很好,但是"methodfromdepclass"是参数化方法,因此,我想创建一个单独的模拟对象,该对象根据将什么参数传递给methodfromdepclass来返回不同的值.

Which is fine, but "methodfromdepclass" is a parameterized method, and as such I want to create a single mock object where depending on what arguments are passed to methodfromdepclass it returns different values.

我想要此参数化行为的原因是我想创建多个ClassUnderTest实例,这些实例包含不同的值(其值由从嘲笑对象返回的值产生).

The reason I want this parameterized behaviour is I want to create multiple instances of ClassUnderTest that contain different values (the values of which are produced by what gets returned from the mockobj).

Kinda我在想什么(这当然是行不通的):

Kinda what I'm thinking (this of course does not work):

mockobj = Mock(spec=MyDependencyClass)
mockobj.methodfromdepclass.ifcalledwith(42).return_value = "you called me with arg 42"
mockobj.methodfromdepclass.ifcalledwith(99).return_value = "you called me with arg 99"

assertTrue(mockobj.methodfromdepclass(42), "you called me with arg 42")
assertTrue(mockobj.methodfromdepclass(99), "you called me with arg 99")

cutinst1 = ClassUnderTest(mockobj, 42)
cutinst2 = ClassUnderTest(mockobj, 99)

# now cutinst1 & cutinst2 contain different values

如何实现这种"ifwithwith"语义?

How do I achieve this "ifcalledwith" kind of semantics?

推荐答案

尝试side_effect

def my_side_effect(*args, **kwargs):
    if args[0] == 42:
        return "Called with 42"
    elif args[0] == 43:
        return "Called with 43"
    elif kwargs['foo'] == 7:
        return "Foo is seven"

mockobj.mockmethod.side_effect = my_side_effect

这篇关于带有多次调用方法的Python Mock对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆