获取Python响应后的Mock requests.json

获取Python响应后的Mock requests.json,python,unit-testing,python-unittest.mock,Python,Unit Testing,Python Unittest.mock,我有一个测试: 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},

我有一个测试:

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\u product\u info()
以返回测试中的
return\u值。我试过模拟
requests.json
requests.get.json
,这两个属性都没有错误,我模拟了
文件.MyClient.get\u product\u info
,这不会导致错误,但不起作用,它返回真实数据


我如何模拟这个使用请求库的
get\u product\u info

您应该可以只修补
get\u product\u info()

只需将
\uuuu main\uuuu
切换到您模块的名称。你可能也会发现这很有用

from unittest.mock import patch


class MyClient(object):
    def get_product_info(self):
        return 'x'

with patch('__main__.MyClient.get_product_info', return_value='z'):
    client = MyClient()
    info = client.get_product_info()
    print('Info is {}'.format(info))
    # >> Info is z