我正在尝试为类似于下面的类编写单元测试。
import boto
class ToBeTested:
def location(self, eb):
return eb.create_storage_location()
def some_method(self):
eb = boto.beanstalk.connect_to_region(region, access_key, secret_key)
location(eb)
有没有办法模拟 boto.beanstalk.connect_to_region 返回值,最后模拟 create_storage_location ?我是新手修补和模拟python,所以我不知道我怎么能这样做。如果有办法,有人可以告诉我吗?
非常感谢!
答案 0 :(得分:4)
这个想法是修补connect_to_region()
以便它返回一个Mock
对象,然后你可以在模拟上定义你想要的任何方法,例如:
import unittest
from mock import patch, Mock
class MyTestCase(unittest.TestCase):
@patch('boto.beanstalk.connect_to_region')
def test_boto(self, connect_mock):
eb = Mock()
eb.create_storage_location.return_value = 'test'
connect_mock.return_value = eb
to_be_tested = ToBeTested()
# assertions
另见:
希望有所帮助。