避免将第二个参数传递给使用模拟补丁

2024-04-18 07:56:34 发布

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

我在模仿我的RpcClient类进行所有单元测试,如下所示:

import unittest2
from mock import patch

@patch('listeners.RpcClient')
class SomeTestCase(unittest2.TestCase):

    test_something(self, mock_api):
        ...

    test_something_else(self, mock_api):
        ...

对于我的大多数测试,我不想使用mock对象做任何断言,我只想修补这个类,这样RpcClient就不会尝试连接和激发对我的每个测试的请求(我将它连接到我的一个模型上的post save事件)。你知道吗

我能避免把mock_api传入我的每一个测试吗?


Tags: fromtestimportselfapi单元测试mocktestcase
3条回答

最后我用patcher.start()setUp中进行了模拟:

def setUp(self):
    self.rpc_patcher = patch('listeners.RpcClient')
    self.MockClass = rpc_patcher.start()

def tearDown(self):
    self.rpc_patcher.stop()

所以我不必装饰我的任何测试用例,也不必为我的测试添加任何额外的参数。你知道吗

更多信息:

http://docs.python.org/dev/library/unittest.mock#patch-methods-start-and-stop

你能给mock\u api设置一个默认参数吗?你知道吗

def test_something(self, mock_api=None):
    ...

def test_something_else(self, mock_api=None):

在调用SUT时,可以使用mock.patch作为上下文管理器。比如:

import unittest2
from mock import patch


class SomeTestCase(unittest2.TestCase):

    def call_sut(self, *args, **kwargs):
        with mock.patch('listeners.RpcClient'):
            # call SUT

    def test_something(self):
        self.call_sut()
        # make assertions

    def test_something_else(self):
        self.call_sut()
        # make assertions

相关问题 更多 >