Python unittest 中的 setUp() 和 setUpClass() 有什么区别? [英] What is the difference between setUp() and setUpClass() in Python unittest?

查看:23
本文介绍了Python unittest 中的 setUp() 和 setUpClass() 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python unittest 框架中的 setUp()setUpClass() 有什么区别?为什么要以一种方法处理设置而不是另一种方法?

What is the difference between setUp() and setUpClass() in the Python unittest framework? Why would setup be handled in one method over the other?

我想了解在 setUp()setUpClass() 函数以及 tearDown() 函数中完成了哪些设置部分code> 和 tearDownClass().

I want to understand what part of setup is done in the setUp() and setUpClass() functions, as well as with tearDown() and tearDownClass().

推荐答案

当您的班级中有多个测试方法时,差异就会显现出来.setUpClasstearDownClass 为全班运行一次;setUptearDown 在每个测试方法之前和之后运行.

The difference manifests itself when you have more than one test method in your class. setUpClass and tearDownClass are run once for the whole class; setUp and tearDown are run before and after each test method.

例如:

class Example(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print("setUpClass")

    def setUp(self):
        print("setUp")

    def test1(self):
        print("test1")

    def test2(self):
        print("test2")

    def tearDown(self):
        print("tearDown")

    @classmethod
    def tearDownClass(cls):
        print("tearDownClass")

当你运行这个测试时,它会打印:

When you run this test, it prints:

setUpClass
setUp
test1
tearDown
.setUp
test2
tearDown
.tearDownClass

(点 (.) 是 unittest 在测试通过时的默认输出.)观察 setUptearDown 出现在 test1 and test2 之前和之后,而 setUpClasstearDownClass> 只出现一次,在整个测试用例的开头和结尾.

(The dots (.) are unittest's default output when a test passes.) Observe that setUp and tearDown appear before and after test1 and test2, whereas setUpClass and tearDownClass appear only once, at the beginning and end of the whole test case.

这篇关于Python unittest 中的 setUp() 和 setUpClass() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆