简体   繁体   English

在不是 python 参数的方法中模拟 object

[英]Mock an object in a method that is not a parameter in python

(i'm a python newbie) (我是 python 新手)

I was looking at: Mocking out objects and methods我在看: 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:我想知道我是否可以在不作为参数传递的 python 方法中替换 object,假设我的方法是这样的:

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我希望测试 mypymethod 但是我希望os.path 在这种情况下在我从我的测试方法中调用它时返回“yourmockresult”

anyway i can do this?反正我能做到吗? thanks!!谢谢!!

You should use Michael Foord's Mock module for the same.您应该使用 Michael Foord 的Mock模块。

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

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

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