简体   繁体   中英

In Python, how do I use voidspace to mock out just one method (out of many) of an object?

eg

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()  

I expect the console to output:

 Hello!

Okay, apparently the documentation just goes around in roundabouts but in fact this page contains the solution:

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

To supplement the weak documentation (high on words, low on content... such a shame) that uses confusing variable / function names in the the example, the correct way to mock the method is so:

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()  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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