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_product_info()返回return_value测试中的数据。我尝试过模拟requests.json,并且requests.get.json在没有属性时都出现错误,我已经模拟the_file.MyClient.get_product_info了不会导致错误但不起作用,它返回真实数据。

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

4

1 回答 1

1

你应该可以只打补丁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__到您的模块的名称。您可能还会发现patch.object有用。

于 2017-04-14T04:51:27.640 回答