2

我一定很累,因为肯定有一种简单的方法可以做到这一点。但是我已经阅读了 pytest 文档并且无法弄清楚这个简单的用例。

我有一个小包要测试:

class MyClass:
    def __init__(self):
        pass
    def my_method(self, arg):
        pass

def the_main_method():
    m = MyClass()
    m.my_method(123)

我想确保(1)创建一个实例,并使用正确的参数调用MyClass(2) 。my_method

所以这是我的测试:

from unittest.mock import patch

@patch('mypkg.MyClass', autospec=True)
def test_all(mocked_class):

    # Call the real production code, with the class mocked.
    import mypkg
    mypkg.the_main_method()

    # Ensure an instance of MyClass was created.
    mocked_class.assert_called_once_with()

    # But how do I ensure that "my_method" was called?
    # I want something like mocked_class.get_returned_values() ...

我知道每次生产代码调用框架时都会产生一个新的模拟实例MyClass()unittest

但是我如何获得这些实例呢?

我想写一些类似的东西:

the_instance.assert_called_once_with(123)

但我从哪里得到the_instance

4

1 回答 1

1

好吧,令我惊讶的是,无论您调用多少次构造函数,都只创建了一个模拟实例(:

我能写的是:

mocked_class.return_value.my_method.assert_called_once_with(123)

但是,return_value它并不代表一个返回值——它会为所有创建的实例积累信息。

在我看来,这是一种相当深奥的方法。我认为它是从一些疯狂的 Java 模拟库中复制而来的(:

如果你想捕获单个返回的对象,你可以使用.side_effect返回任何你想要的,并将它记录在你自己的列表中,等等。

于 2017-02-16T19:11:15.363 回答