在Python中,如何使用空洞空间来模拟对象中的一个方法(多个方法中)?

时间:2013-09-10 21:45:02

标签: python mocking

e.g。

class Foobar:
    def func():
        print('This should never be printed.')
    def func2():
        print('Hello!')

def test_mock_first_func():
    foobar = Foobar()
    # !!! do something here to mock out foobar.func()
    foobar.func()
    foobar.func2()  

我希望控制台输出:

 Hello!

1 个答案:

答案 0 :(得分:0)

好的,显然文档只是在环形交叉路口出现,但事实上这个页面包含解决方案:

http://www.voidspace.org.uk/python/mock/examples.html#mocking-unbound-methods

为了补充在示例中使用令人困惑的变量/函数名称的弱文档(高字,低内容......如此羞耻),模拟方法的正确方法是:

class Foobar:
    def func():
        print('This should never be printed.')
    def func2():
        print('Hello!')

def test_mock_first_func():
    with patch.object(Foobar, 'func', autospec=True) as mocked_function:
        foobar = Foobar()
        foobar.func()  # This function will do nothing; we haven't set any expectations for mocked_function!
        foobar.func2()