how to specify test specific setup and teardown in python unittest(如何在python unittest中指定特定于测试的设置和拆卸)
本文介绍了如何在python unittest中指定特定于测试的设置和拆卸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要使用两个不同的设置创建单元测试,并使用两个不同的测试在同一个类中创建拆卸方法。
每个测试都将使用其在python单元测试框架中的特定设置和拆卸方法。
有人能帮帮我吗?
class processtestCase(unittest.TestCase):
print "start the process test cases "
def setUp1(self):
unittest.TestCase.setUp(self)
def test_test1(self):
"test Functinality"
def tearDown1(self):
unittest.TestCase.tearDown(self)
def setUp2(self):
unittest.TestCase.setUp2(self)
def test_test2(self):
"test Functinality"
def tearDown2(self):
unittest.TestCase.tearDown2(self) '
if __name__ == '__main__':
unittest.main()
推荐答案
在问题中,您提到有两个测试,每个测试都有自己的设置和拆除。至少有两条路可走:
您可以在每个测试中嵌入setUp和tearDown代码:
class FooTest(unittest.TestCase):
def test_0(self):
... # 1st setUp() code
try:
... # 1st test code
except:
... # 1st tearDown() code
raise
def test_1(self):
... # 2nd setUp() code
try:
... # 2nd test code
except:
... # 2nd tearDown() code
raise
或者,您也可以将类拆分为两个类:
class FooTest0(unittest.TestCase):
@classmethod
def setUp(cls):
...
@classmethod
def tearDown(cls):
...
def test(self):
...
第一个选项的类更少、更短、更直接。第二种方法更干净利落地去耦合设置装置,并清理它,然后是测试代码本身。它还在未来增加更多的测试。
您应该根据您的具体情况和个人喜好来判断取舍。
这篇关于如何在python unittest中指定特定于测试的设置和拆卸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:如何在python unittest中指定特定于测试的设置和拆卸
基础教程推荐
猜你喜欢
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
