GCode21
GCode21

Reputation: 74

How to mock a function called by an object of a class?

I will start off by admitting that I have just got into python mock or any mock for that matter for a day or two.

So I have a python file that has a class in it:

MyFileA.py

class A:
    def Afunc():
        #do smthn

Now I want to mock a different script that uses this MyFileA.py

MyFileB.py

from MyFileA import A

def Bfunc():
    Aobj = A()
    ReturnVal = Aobj.Afunc()

How do I mock the statement Aobj.Afunc() to return a specific value?

Also, I am exclusively using decorators for mock method so I am expecting solutions in that format only.

Upvotes: 3

Views: 2534

Answers (1)

Lin Du
Lin Du

Reputation: 102587

You can use mock.patch to mock class A and Afunc and its returned value.

E.g.

MyFileA.py:

class A:
    def Afunc():
        print('do smthn')

MyFileB.py:

from MyFileA import A


def Bfunc():
    Aobj = A()
    ReturnVal = Aobj.Afunc()
    return ReturnVal

test_MyFileB.py:

import unittest
from MyFileB import Bfunc
from unittest import mock


class TestMyFileB(unittest.TestCase):
    @mock.patch('MyFileB.A')
    def test_Bfunc(self, mock_A):
        a_instance = mock_A.return_value
        a_instance.Afunc.return_value = "mocked value"
        actual = Bfunc()
        self.assertEqual(actual, 'mocked value')
        mock_A.assert_called_once()
        a_instance.Afunc.assert_called_once()


if __name__ == '__main__':
    unittest.main()

unit test result with coverage report:

.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK
Name                                         Stmts   Miss  Cover   Missing
--------------------------------------------------------------------------
src/stackoverflow/63429593/MyFileA.py            3      1    67%   3
src/stackoverflow/63429593/MyFileB.py            5      0   100%
src/stackoverflow/63429593/test_MyFileB.py      13      0   100%
--------------------------------------------------------------------------
TOTAL                                           21      1    95%

Upvotes: 2

Related Questions