0

例如

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!
4

1 回答 1

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()  
于 2013-09-10T22:05:56.893 回答