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
Mocking the return value of the method sum
def sum(a,b):
return a+b
sum(2,3)
import inspect
inspect.getmodule(sum)
from unittest.mock import patch
Patch the method with its import path and specify the new return value
@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
test_sum()
sum(2,3) == 9