【问题标题】:Using MagicMock to test the inner components of a method使用 MagicMock 测试方法的内部组件
【发布时间】:2017-07-05 20:57:49
【问题描述】:

我不熟悉使用模拟库和一般的单元测试。我想我了解模拟库的工作原理,但我认为我的方法有问题。

假设我有一个类 Foo 有一个方法 addFoo(bar1, bar2)addFoo 在 foo 中调用其他“私有”方法,但也可以在代码的各个部分引发异常......即

class Foo:
    def __init__(self):
         # This creates lots of dependencies

    def _inner1(self, bar):
        if this_doesnt_work:
           return None
        return modified_bar1

    def _inner2(self, bar2):
        if this_doesnt_work:
           return None
        return modified_bar2

    def addFoo(bar1, bar2):
        if self._inner1(bar1) and self._inner2(bar2):
           #do something
        else:
           raise SomeException

当我进行单元测试时,我目前所做的是在我的单元测试设置中模拟 Foo.__init__ 并将 return_value 设置为 None。这有效,并允许我在没有所有外部依赖项的情况下对类中的方法运行测试,并且只需使用我模拟的 Foo.__init__ 实例模拟任何类属性。

完成之后,如果我想对addFoo 进行单元测试,我会执行以下操作(跳过一堆步骤):

@patch.object(Foo, '_inner2')
@patch.object(Foo, '_inner1')
def test_inner1_exception(self, mock_inner1, mock_inner2):
    mock_inner1.side_effect = Exception
    # then do some asserts to make sure it worked

问题 如果代码如下所示,我如何在addFoo 中测试异常:

def addFoo(bar1, bar2):
    bars = self._getBars() #something that returns a list
    my_modified_bar_list = []
    for bar in bars:
        my_modified_bar_list.append(self._inner1(bar))

    if len(my_modified_bar_list) == 0:
        raise SomeException

在这种情况下,当 SomeException 依赖于我的方法中某个数组产生的值时,我该如何测试它?

【问题讨论】:

    标签: python python-2.7 unit-testing mocking


    【解决方案1】:

    如果你正在使用pytest,你可以assert about expected exceptions如下:

    @patch('Foo._getBars', return_value=[])
    def test_addFoo_exception(self):
        foo = Foo()
        with pytest.raises(SomeException):
            foo.addFoo(Mock(), Mock())
    

    正如上面的 sn-p 所示,通过模拟 _getBars,您可以控制返回的内容,因此可以强制触发代码中的异常条件,在本例中是一个空列表。

    我写了一个简短的post with common unit testing pitfalls in Python,您可能会觉得有用。

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 1970-01-01
      • 2020-07-17
      • 2016-03-28
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      相关资源
      最近更新 更多