Unittest setUp/tearDown 用于多个测试 [英] Unittest setUp/tearDown for several tests

查看:44
本文介绍了Unittest setUp/tearDown 用于多个测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有在测试场景开始/结束时触发的函数?在每次测试之前/之后都会触发 setUp 和 tearDown 函数.

Is there a function that is fired at the beginning/end of a scenario of tests? The functions setUp and tearDown are fired before/after every single test.

我通常想要这个:

class TestSequenceFunctions(unittest.TestCase):

    def setUpScenario(self):
        start() #launched at the beginning, once

    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

    def test_sample(self):
        with self.assertRaises(ValueError):
            random.sample(self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)

    def tearDownScenario(self):
        end() #launched at the end, once

目前,这些setUp和tearDown是单元测试,分布在我所有的场景中(包含很多测试),一个是第一个测试,另一个是最后一个测试.

For now, these setUp and tearDown are unit tests and spread in all my scenarios (containing many tests), one is the first test, the other is the last test.

推荐答案

截至 2.7(根据 文档) 你得到 setUpClasstearDownClass 它们分别在给定类中的测试运行之前和之后执行.或者,如果您在一个文件中有一组,您可以使用 setUpModuletearDownModule (文档).

As of 2.7 (per the documentation) you get setUpClass and tearDownClass which execute before and after the tests in a given class are run, respectively. Alternatively, if you have a group of them in one file, you can use setUpModule and tearDownModule (documentation).

否则你最好的选择可能是创建你自己的派生 TestSuite 并覆盖run().所有其他调用将由父级处理,而 run 将围绕调用父级的 run 方法调用您的设置和拆卸代码.

Otherwise your best bet is probably going to be to create your own derived TestSuite and override run(). All other calls would be handled by the parent, and run would call your setup and teardown code around a call up to the parent's run method.

这篇关于Unittest setUp/tearDown 用于多个测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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