python - PyUnit 拆解和设置与 __init__ 和 __del__

标签 python unit-testing

在使用 pyUnit 测试框架时,使用 tearDown 和 setUp 与使用 __init____del__ 有区别吗?如果是这样,它到底是什么?首选的使用方法是什么?

最佳答案

setUp 在每次测试前调用,tearDown 在每次测试后调用。 __init__ 在类被实例化时被调用一次——但是因为 a new TestCase instance is created for each individual test method , __init__ 是 每次测试也调用一次。

写unit时一般不需要定义__init____del__ 测试,尽管您可以使用 __init__ 来定义许多测试使用的常量。


此代码显示调用方法的顺序:

import unittest
import sys

class TestTest(unittest.TestCase):

    def __init__(self, methodName='runTest'):
        # A new TestTest instance is created for each test method
        # Thus, __init__ is called once for each test method
        super(TestTest, self).__init__(methodName)
        print('__init__')

    def setUp(self):
        #
        # setUp is called once before each test
        #
        print('setUp')

    def tearDown(self):
        #
        # tearDown is called once after each test
        #
        print('tearDown')

    def test_A(self):
        print('test_A')

    def test_B(self):
        print('test_B')

    def test_C(self):
        print('test_C')



if __name__ == '__main__':
    sys.argv.insert(1, '--verbose')
    unittest.main(argv=sys.argv)

打印

__init__
__init__
__init__
test_A (__main__.TestTest) ... setUp
test_A
tearDown
ok
test_B (__main__.TestTest) ... setUp
test_B
tearDown
ok
test_C (__main__.TestTest) ... setUp
test_C
tearDown
ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

关于python - PyUnit 拆解和设置与 __init__ 和 __del__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2344772/

相关文章:

python - 谷歌应用引擎中的静态文件在哪里?

python - 如果您已经刷新以使内容在意外重启后仍然存在,是否需要调用 close ?

python - 使用 django.test.client.Client 与提交输入类型关联的 POST 值

c++ - 单元测试框架——POS应用

python - CEFPython 应用程序 - 如何从 HTML 调用 JSON 文件

python - 如何构建 Python C 扩展,以便我可以从模块中导入它

python - Powershell 和 Python - 如何以管理员身份运行命令

unit-testing - 有没有办法在普通计算机上运行为嵌入式微 Controller 设计的C代码?

ruby-on-rails - Rails Rake 测试 : Errors running test:units! #<RuntimeError: 命令失败,状态为

java - 使用 JPA 和 JTA 的单元测试代码