Mocking with patch

1) Mock is used to change the default return value of a method at certain parts of the code

2) This is mainly used in unit tests where we want to mock when certain parts of the code that require external connections. For example, we may want to mock that a database is connected without actually connecting

3) This can also be used to counting the number of calls made to a method

Example

Mocking the return value of the method sum

In [5]:
def sum(a,b):
    return a+b

sum(2,3)
Out[5]:
5
In [12]:
import inspect
inspect.getmodule(sum)
Out[12]:
<module '__main__'>
In [6]:
from unittest.mock import patch

Patch the method with its import path and specify the new return value

In [21]:
@patch('__main__.sum', return_value=9)
def test_sum(s):
    return sum(2,3) == 9
# s.call_count gives the number of calls made to the method sum
In [18]:
test_sum()
Out[18]:
True
In [20]:
sum(2,3) == 9
Out[20]:
False