unittest.mock断言错误:预期与实际调用不符问题求助
Hey there! Let's work through fixing that AssertionError: Expected and actual call not same issue you're hitting with unittest.mock. First, let's recap your setup to make sure we're on the same page:
Your Project Structure
project/ ├── src/ │ ├── __init__.py │ └── function.py └── tests/ ├── __init__.py └── test_function.py
Your Test Code Snippet
import unittest from unittest import mock from ..src.function import get_subscriptions from ..src import function class TestCheckOrder(unittest.TestCase): @mock.patch.object(function, 'table') def test_get_subscriptions_success(self, mocked_table): # ... your test logic here ... # Throws AssertionError: Expected and actual call not same
This error almost always boils down to a mismatch between what you expected your mocked table to be called with, and what it was actually called with during the test. Let's break down the most common fixes:
1. Verify Call Parameters Match
The #1 culprit is mismatched arguments. For example, if you wrote mocked_table.assert_called_with(123) but your actual code calls table(456, "extra_param"), the assertion will fail.
Fix:
Add a print statement to see exactly how table was called, then adjust your assertion to match:
def test_get_subscriptions_success(self, mocked_table): # ... run your test logic ... print("Actual call details:", mocked_table.call_args) # This shows the real arguments # Update your assertion to match the output from the print statement mocked_table.assert_called_with(user_id=1, status="active") # Example matching args
2. Ensure You're Patching the Right Object
Sometimes the patch targets the wrong instance of table. If get_subscriptions imports table from a different module than the one you're patching, your mock won't take effect.
Fix:
Double-check that you're patching the exact table object used by get_subscriptions. If get_subscriptions lives in src/function.py and uses the local table variable there, your current patch (@mock.patch.object(function, 'table')) is correct—but make sure you're running tests from the project root (use python -m unittest tests.test_function instead of running the test file directly) to avoid import path issues.
3. Check for Multiple Calls or Wrong Call Order
If you're using assert_called_once_with(...) but table gets called multiple times, or if you're asserting the wrong call in a sequence, you'll get this error.
Fix:
View all recorded calls with call_args_list to debug:
print("All calls to table:", mocked_table.call_args_list) # If you just need to verify one of the calls matches, use: mocked_table.assert_any_call(expected_arg1, expected_arg2)
4. Confirm Mock Return Values Are Set Correctly
If you didn't set a return value for mocked_table, your code might take an unexpected path that changes how table is called later.
Fix:
Set a realistic return value before running your test function:
def test_get_subscriptions_success(self, mocked_table): # Set mock return value to match what your code expects mocked_table.return_value = {"subscriptions": ["basic", "premium"]} # Run the function under test result = get_subscriptions(user_id=123) # Now assert the call mocked_table.assert_called_with(user_id=123)
Example Fixed Test Code
Putting it all together, here's a revised version of your test with debugging and proper setup:
import unittest from unittest import mock from ..src.function import get_subscriptions from ..src import function class TestCheckOrder(unittest.TestCase): @mock.patch.object(function, 'table') def test_get_subscriptions_success(self, mocked_table): # Configure mock behavior mocked_table.return_value = {"user_id": 1, "subscriptions": ["premium"]} # Execute the function we're testing result = get_subscriptions(user_id=1) # Debug: print actual call to verify print("Actual call args:", mocked_table.call_args) # Assert the mock was called correctly mocked_table.assert_called_with(user_id=1) # Verify the function returns the expected result self.assertEqual(result, ["premium"])
Remember to run your tests from the project root directory to avoid relative import errors. If you're using pytest, add the -s flag to see the print output.
内容的提问来源于stack exchange,提问作者Vivek

