本文介绍了如何在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中指定特定于测试的设置和拆卸
发布评论