如何在python unittest中指定特定于测试的设置和拆卸

编程入门 行业动态 更新时间:2024-10-24 21:22:07
本文介绍了如何在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中指定特定于测试的设置和拆卸

本文发布于:2023-11-27 21:01:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   如何在   python   unittest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!