【发布时间】:2017-04-13 20:49:02
【问题描述】:
我有测试:
class MyTests(TestCase):
def setUp(self):
self.myclient = MyClient()
@mock.patch('the_file.requests.json')
def test_myfunc(self, mock_item):
mock_item.return_value = [
{'itemId': 1},
{'itemId': 2},
]
item_ids = self.myclient.get_item_ids()
self.assertEqual(item_ids, [1, 2])
在我拥有的文件中
import requests
class MyClient(object):
def get_product_info(self):
response = requests.get(PRODUCT_INFO_URL)
return response.json()
我的目标是模拟 get_product_info() 以在测试中返回 return_value 数据。我试过模拟requests.json和requests.get.json,都没有属性错误,我模拟了the_file.MyClient.get_product_info,它不会导致错误但不起作用,它会返回真实数据。
如何模拟这个使用 requests 库的get_product_info?
【问题讨论】:
标签: python unit-testing python-unittest.mock