Python Mock object with method called multiple times

A little sweeter:

mockobj.method.side_effect = lambda x: {123: 100, 234: 10000}[x]

or for multiple arguments:

mockobj.method.side_effect = lambda *x: {(123, 234): 100, (234, 345): 10000}[x]

or with a default value:

mockobj.method.side_effect = lambda x: {123: 100, 234: 10000}.get(x, 20000)

or a combination of both:

mockobj.method.side_effect = lambda *x: {(123, 234): 100, (234, 345): 10000}.get(x, 20000)

and merrily on high we go.


I've ran into this when I was doing my own testing. If you don't care about capturing calls to your methodfromdepclass() but just need it to return something, then the following may suffice:

def makeFakeMethod(mapping={}):
    def fakeMethod(inputParam):
        return mapping[inputParam] if inputParam in mapping else MagicMock()
    return fakeMethod

mapping = {42:"Called with 42", 59:"Called with 59"}
mockobj.methodfromdepclass = makeFakeMethod(mapping)

Here's a parameterized version:

def makeFakeMethod():
    def fakeMethod(param):
        return "Called with " + str(param)
    return fakeMethod

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