如何在Django中为几个测试模拟一个类

时间:2015-02-19 22:13:01

标签: python django unit-testing mocking

我有一个通过HTTP调用远程服务的类。现在,这个类检测它是否在" TESTING"模式和行为相应:同时"测试"它不会将实际请求发送到远程服务,它只返回而不执行任何操作。

class PushService(object):

    def trigger_event(self, channel_name, event_name, data):
        if satnet_cfg.TESTING:
            logger.warning('[push] Service is in testing mode')
            return
        self._service.trigger(channel_name, event_name, data)

多个测试通过调用此方法调用最终的部分代码。我的问题如下:

1. Do I have to patch this method/class for every test that, for some reason, also invoke that method?
2. Is it a good practice to try to patch it in the TestRunner?

1 个答案:

答案 0 :(得分:1)

如果您需要为所有测试做补丁,可以使用setUpClass方法执行此操作:

class RemoteServiceTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.patchers = []
        patcher = patch('application.PushService.trigger_event')
        cls.patchers.append(patcher)
        trigger_mock = patcher.start()
        trigger_mock.return_value = 'Some return value'

    @classmethod
    def tearDownClass(cls):
        for patcher in cls.patchers:
            patcher.stop()

    def test1(self):
        # Test actions

    def test2(self):
        # Test actions

    def test3(self):
        # Test actions
每个类调用一次{p> setUpClass(本例中为测试套件)。在此方法中,您可以设置所有测试都需要使用的所有修补程序。