python data_error ai_generated true

AssertionError: 预期 'mock_method' 被调用一次。实际调用 2 次。

AssertionError: Expected 'mock_method' to be called once. Called 2 times.

ID: python/pytest-mock-not-reset-between-tests

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-09-05首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

mock 对象在测试之间未重置,因此调用计数从先前测试累积。这发生在 mock 定义在模块级别或通过类属性共享时。

English

A mock object was not reset between tests, so call counts accumulated from previous tests. This happens when mocks are defined at module level or shared via class attributes.

generic

解决方案

  1. 95% 成功率
    @pytest.fixture
    def mock_service():
        return MagicMock()
    
    def test_one(mock_service):
        mock_service.method()
        mock_service.method.assert_called_once()
  2. 93% 成功率
    def test_one(mocker):
        mock = mocker.patch('module.func')
        mock()
        mock.assert_called_once()

无效尝试

常见但无效的做法:

  1. 75% 失败

    If a test fails before reaching the reset line, the mock remains dirty for the next test. Also error-prone to maintain.

  2. 85% 失败

    This changes the assertion but does not fix the accumulated call count. The assertion will still fail.