如何模拟一个类的所有方法 - Python

时间:2021-02-28 16:42:38

标签: python class patch fixtures

我正在尝试使用补丁来模拟整个课程。 想象一下,该类是MyClass(),其方法 foo()bar() 都返回一个布尔值。

我尝试的方式是在 conftest.py 中包含fixture

@pytest.fixture(scope="session")
def mock_myclass() -> MagicMock:
    with patch("module.file.MyClass") as myclass_mocked:
         myclass_mocked.foo.return_value = True
         myclass_mocked.bar.return_value = True
         yield myclass_mocked

然后我有一个名为 test_some_other_function 的测试,例如

def test_some_other_function(mock_myclass: MagicMock, x: int, y:float):
    some_other_function(x,y)

其中 some_other_function 不是 MyClass 的成员,而是使用来自 MyClass 的对象并同时调用 foobar 方法。但是,当我尝试 mock_myclass.foo.asseert_called()mock_myclass.bar.asseert_called() 时,我总是收到以下错误,即使我确定测试到达了调用 foobar 的地方。< /p>

 AssertionError: Expected 'foo' to have been called.

我希望这很清楚。谢谢!

0 个答案:

没有答案
相关问题