【问题标题】:Python Unittest structurePython单元测试结构
【发布时间】:2022-11-08 18:17:27
【问题描述】:

所以在我的项目中,我有一个很长的(~1000 行)TestCase 模块,只有 1 个测试用例。
我想把它分成 3-4 个单独的 TestCase 模块(单独的文件)。
但是我怎样才能做一个常见的setUp分享固定装置所有模块?
使用一些进口夹具?
我在我的长模块中使用setUpClass 和一个TestCase。
请指教。

【问题讨论】:

    标签: python python-unittest


    【解决方案1】:

    你可以做的是定义一个父类,例如

    class CommonTestCase(unittest.TestCase):
        def setUpClass(self):
            # Do setup or anything else here
    

    然后在其他文件或情况下,您可以使用继承来使用父类CommonTestCase 中的相同设置步骤:

    from my_package import CommonTestCase
    
    class MyTestCaseA(CommonTestCase):
        def test_this(self):
            # Test implementation
    
    class MyTestCaseB(CommonTestCase):
        def test_that(self):
            # Test implementation
    

    【讨论】:

    • 看起来不错,但如果只是在 CommonTestCase 中插入 setUpClass 方法而不是在在里面?是一样的吗?
    • @ruslanway 我会说使用setUpClass首选.在我看来,没有必要覆盖TestCase.__init__
    • 当然,它在功能上是相同的。在一个项目中,我从__init__ 中提取了这个用于设置一些变量,这是一个干净的解决方案,但是我会修改答案以减少任何误解。
    猜你喜欢
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2013-12-30
    相关资源
    最近更新 更多