Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 避免使用mock.patch将第二个参数传递给每个单元测试_Python_Unit Testing_Mocking - Fatal编程技术网

Python 避免使用mock.patch将第二个参数传递给每个单元测试

Python 避免使用mock.patch将第二个参数传递给每个单元测试,python,unit-testing,mocking,Python,Unit Testing,Mocking,我在模仿我的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): ... 对于我的

我在模仿我的
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\u api
传递到我的每一个测试中吗?

您可以将默认参数设置为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

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

因此,我不必修饰任何测试用例,也不必向测试中添加任何额外的参数

更多信息:

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

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