如何在 Django 中为多个测试模拟 class

How to mock up a class for several tests in Django

我有一个 class 通过 HTTP 调用远程服务。现在,这个 class 检测它是否处于 "TESTING" 模式下的 运行 并采取相应的行动:虽然 "TESTING" 它不会向远程服务发送实际请求,它只是 returns 根本不执行任何操作。

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?

如果您需要为所有测试打补丁,您可以在 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

setUpClass 每 class 调用一次(在本例中为测试套件)。在此方法中,您可以设置所有测试需要使用的所有修补程序。