7hi*_*4g0 18 python testing unit-testing python-unittest
当我创建一个时unittest.TestCase,我可以定义一个setUp()在该测试用例中的每个测试之前运行的函数.是否可以跳过setUp()单个特定测试?
想要跳过setUp()给定测试可能不是一个好习惯.我对单元测试相当新,欢迎任何有关该主题的建议.
vic*_*rtv 14
您可以使用 Django 的 @tag 装饰器作为跳过 setUp 的标准
# import tag decorator
from django.test.util import tag
# The test which you want to skip setUp
@tag('skip_setup')
def test_mytest(self):
assert True
def setUp(self):
method = getattr(self,self._testMethodName)
tags = getattr(method,'tags', {})
if 'skip_setup' in tags:
return #setUp skipped
#do_stuff if not skipped
Run Code Online (Sandbox Code Playgroud)
除了跳过,您还可以使用标签进行不同的设置。
PS 如果你没有使用 Django,那么该装饰器的源代码非常简单:
Run Code Online (Sandbox Code Playgroud)def tag(*tags): """ Decorator to add tags to a test class or method. """ def decorator(obj): setattr(obj, 'tags', set(tags)) return obj return decorator
Ste*_*ski 10
来自docs(斜体矿):
unittest.TestCase.setUp()调用准备测试夹具的方法.在调用测试方法之前立即调用它; 此方法引发的任何异常都将被视为错误而非测试失败. 默认实现什么都不做.
因此,如果您不需要任何设置,请不要覆盖unittest.TestCase.setUp.
但是,如果您的某个test_*方法不需要设置而其他方法不需要,我建议将其放在单独的类中.
| 归档时间: |
|
| 查看次数: |
5719 次 |
| 最近记录: |