6

我在一个类中有几个测试方法,它们对对象使用一种类型的修补,所以我用类装饰器进行了修补。对于另一种方法,我想以不同的方式修补同一个对象。我尝试了以下方法,但是尽管方法本身被不同的补丁装饰,但作为类装饰器制作的补丁仍然有效。我希望方法补丁覆盖类补丁。为什么不是这样?

在这种特殊情况下,我可以删除类补丁并修补单个方法,但这将是重复的。如何实现这种覆盖(方法覆盖类补丁)机制?

from unittest TestCase
from unittest import mock

@mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('testing'))
class SwitchViewTest(TestCase):

    def test_use_class_patching(self):
        # several other methods like this
        # test code ..

    @mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('custom'))
    def test_override_class_patching(self):
        # test code ...
4

3 回答 3

5

使用with

def test_override_class_patching(self):
    with mock.patch('my_module.cls.method') as mock_object:
        mock_object.side_effect = RuntimeError('custom')
        # test code ...
于 2020-01-08T10:27:43.810 回答
5

这只有在编写类装饰器以说明方法装饰器的使用时才有效。虽然类装饰器首先出现,但它只能在类对象创建后运行,这发生在所有方法都已定义(和装饰)之后。

类装饰器方法装饰器之后运行,而不是之前。

于 2016-09-23T02:42:15.293 回答
0

我会采取完全不同的方法。

class SwitchViewTest(TestCase):

  class SwitchViewStub(SwitchView):
    """ Stub out class under test """
    def __init__(self):
    """ Bypass Constructor """
      self.args = None
      ... #  Fill in the rest

  def setUp():
    self.helper = self.SwitchViewStub()
    self.helper.method_to_mock = MagicMock(...)
    ...

  def test_override_class_patching(self):
    with mock.patch.object(self.helper, 'method_to_mock', ...):
      ...
于 2016-09-23T16:16:42.967 回答