嘲弄请求.json得到响应后python

2024-04-25 11:36:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有考试

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

在我的档案里

^{pr2}$

我的目标是模拟get_product_info()以返回测试中的return_value数据。我试过模拟requests.jsonrequests.get.json,这两个都是在no属性上出错的,我模拟了{},它不会导致错误,但不起作用,它返回真实的数据。在

我如何模拟这个使用请求库的get_product_info?谢谢你


Tags: 数据selfinfojsonidsgetreturnvalue
1条回答
网友
1楼 · 发布于 2024-04-25 11:36:28

您应该能够只修补get_product_info()。在

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

只需将__main__切换到模块的名称。您可能还发现^{}很有用。在

相关问题 更多 >