简体   繁体   English

Mocking a Python object 没有方法调用

[英]Mocking a Python object without method calls

Imagine a class like so:想象一个 class 像这样:

class Foo():

    def method_1(self):
        bar = Bar()
        bazz = Bazz(bar)
        return bazz.method_2()

For unit testing, how can we mock the Bar object when we never call any methods on it, we're just passing it as a parameter to the Bazz constructor?对于单元测试,当我们从不调用Bar object 的任何方法时,我们如何模拟它,我们只是将它作为参数传递给Bazz构造函数? (Yes, this is not ideal, but this pattern can be found in a top-level class wiring together different objects via dependency injection). (是的,这并不理想,但是这种模式可以在顶层 class 通过依赖注入将不同的对象连接在一起中找到)。

You do call the Bar object, when you execute: bar = Bar() , so you can easily mock it:当您执行: bar = Bar()时,您确实调用了Bar object,因此您可以轻松地模拟它:

mock_bar = mocker.MagicMock(name='Bar')
mocker.patch('foo.Bar', new=mock_bar)
# mock_foo.return_value = the new mocked object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM