【问题标题】:How to mock up a class for several tests in Django如何在 Django 中为多个测试模拟一个类
【发布时间】:2015-02-19 22:13:00
【问题描述】:

我有一个通过 HTTP 调用远程服务的类。现在,这个类检测它是否在“TESTING”模式下运行并采取相应的行动:在“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?

【问题讨论】:

    标签: python django unit-testing mocking


    【解决方案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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 2018-03-14
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多