Sanagi
Sanagi

Reputation: 31

mock a function which is inside another function

I have a function need to be tested, which looks like this:

def f1(var):
    def f2(var):
        # some ops based on var
        # return the result

    ret = f2(var)
    # ops

In my unit test, I wanted to mock the return value of f2, which is inside f1.

I tried to mock it with

f1.f2.return_value

and

f2.return_value

but both were failed.

So how could I mock the f2 inside f1,

or should I refactor the code to move f2 out of f1?

Upvotes: 2

Views: 131

Answers (1)

L. MacKenzie
L. MacKenzie

Reputation: 493

While there is almost certainly some way to access f2 inside of f1 and and make a stub for it in unittesting, it will almost certainly be cleaner to refactor and move f2 out of f1. Something like this:

def f1(var):
    ret = f2(var)

def f2(var):
   # some ops based on var
   return result

Upvotes: 1

Related Questions