I have a simple python code in the VS Code.
under a package my, there are two files aa.py and test_aa.py
aa.py
# Function to be tested
def add(a, b):
return a + b
test_aa.py
from unittest.mock import MagicMock, patch
from my.aa import add
# Test case using MagicMock to mock the add function
@patch('my.aa.add')
def test_add_with_mock(mock_add):
# Set the return value of the mocked add function
mock_add.return_value = 10
# Now any call to the add function will return the value set in the mock
result = add(3, 5)
# Assert that the add function was called with the correct arguments
mock_add.assert_called_once_with(3, 5)
# Assert the result of the add function
assert result == 10
# Run the test
test_add_with_mock()
When I debug to run this unit test, result is 8 rather than 10, seem the mock doesn't work. I am confuse why it fails to mock add().
Any ideas how to fix it?
The reason is that you used:
from my.aa import add
So, you have a reference to the original add
before it got patched. And that's what you call when you do result = add(3, 5)
.
Instead try:
from my import aa
def test(...):
...
result = aa.add(3, 5)
Now your test should lookup the name "add" from the "aa" module namespace, which is where it got patched.