[英]How to mock up a class for several tests in Django
我有一个通过HTTP调用远程服务的类。 现在,该类将检测它是否正在“测试”模式下运行并采取相应的行动:“测试”时,它不会将实际请求发送到远程服务,而只是返回而不执行任何操作。
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
方法中执行此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
(在这种情况下为测试套件)。 在此方法内,您可以设置所有测试都需要使用的所有修补程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.