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

查看:34
本文介绍了具有多次调用方法的 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 的多个实例(这些值由从 mockobj 返回的内容产生).

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

如何实现这种ifcallwith"语义?

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

推荐答案

Try 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天全站免登陆