简体   繁体   中英

Mock an object in a method that is not a parameter in python

(i'm a python newbie)

I was looking at: Mocking out objects and methods

And I was wondering if i can replace an object in a python method which is not passed as a parameter, lets say my method is like this:

def mypymethod(param1)
  myresult = os.path.something
  return myresult

and i wish to test mypymethod however i wish os.path at this case to return "yourmockresult" when i call it from my test method

anyway i can do this? thanks!!

You should use Michael Foord's Mock module for the same.

From the documentation:

>>> from mock import Mock
>>> real = ProductionClass()
>>> real.method = Mock(return_value=3)
>>> real.method(3, 4, 5, key='value')
3
>>> real.method.assert_called_with(3, 4, 5, key='value')

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