如何模拟Python类的对象?

时间:2018-05-11 14:15:05

标签: python-3.x mocking python-unittest

让我说下面的课程;

class CompositionClass(object):
    def __init__(self):
        self._redis = Redis()
        self._binance_client = BinanceClient()

    def do_processing(self, data):
        self._redis.write(data)
        self._binance_client.buy(data.amount_to_buy)

        # logic to actually unittest

        return process_val

我有其他对象在我的ComplexClass中将外部API称为组合。当我对do_processing的逻辑进行单元测试时,我不想调用这些昂贵的API调用。我已经在SO和谷歌中彻底检查过单元测试;所有的例子都很简单,不是很有用。在我的情况下,我如何使用unittest.mock来模拟这些对象?

2 个答案:

答案 0 :(得分:2)

模拟RedisBinanceClient类的一种方法是在测试类中使用patch装饰器,例如:

from unittest import TestCase
from unittest.mock import patch
from package.module import CompositionClass

class TestCompositionClass(TestCase):

    @patch('package.module.BinanceClient')
    @patch('package.module.Redis')
    def test_do_processing(self, mock_redis, mock_binance):
        c = CompositionClass()
        data = [...]
        c.do_processing(data)

        # Perform your assertions

        # Check that mocks were called
        mock_redis.return_value.write.assert_called_once_with(data)
        mock_binance.return_value.buy.assert_called_once_with(data.amount_to_buy)

请注意,指定给@patch的路径是包含CompositionClass及其RedisBinanceClient导入的模块的路径。修补程序在该模块中进行,而不是包含RedisBinanceClient实现的模块。

答案 1 :(得分:0)

您需要将API调用必须返回的值设置为此函数:

from unittest.mock import MagicMock


class Tester(unittest.TestCase):
    def setUp(self):
        pass

    def test_do_processing(self):

        self.API_function = MagicMock(return_value='API_response')
        # test logic