pytest:如何从模拟类中返回(模拟)实例?

时间:2017-02-11 00:38:57

标签: python pytest python-unittest python-unittest.mock

我一定很累,因为肯定有一种简单的方法可以做到这一点。 但我已经阅读了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

1 个答案:

答案 0 :(得分:0)

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

我能写的是:

mocked_class.return_value.my_method.assert_called_once_with(123)

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

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

如果要捕获单个返回的对象,可以使用.side_effect返回所需内容,并将其记录在自己的列表中等。