pytest-mock:嘲笑抽象类

2022-03-01 00:00:00 python python-3.x pytest

问题描述

我正在尝试使以下代码正常工作:

from pytest_mock import mocker

class TestClass(mocker):
  def setup_method(self):
    self.some_mock = SomeAbstractClass()
    self.testsubject = ClassThatIsBeingTested(self.some_mock)

  def test_1(self):
    mocker.patch(self.some_mock, 'some_function', return_value=5)
    assert 5 == self.testsubject.function_that_internally_uses_the_mock()

但我因为尝试实例化抽象类而得到TypeError

如何模拟SomeAbstractClass


解决方案

您可以使用unittest.mock模块(也是Python2.7的mock包)创建模拟实例,而不是尝试修补真实实例:

import sys

if sys.version_info[0] == 2:
    from mock import Mock
else:
    from unittest.mock import Mock

# ...

some_mock = Mock(spec=SomeAbstractClass)
some_mock.some_function.return_value = 5

some_mock.some_function()
# => 5

some_mock.non_existent_function()
# => AttributeError: Mock object has no attribute 'non_existent_function'

这适用于创建任何类的模拟实例,而不仅仅是抽象类。

相关文章