python - unittest 的 setUpClass 类方法能否返回一个值以在其他测试中使用?

标签 python python-3.x unit-testing class

我正在尝试为依赖于模块级数据(JSON 文件)的程序编写单元测试。
所以,我想我会使用 setUpClass 类方法设置一个测试 JSON 文件,然后在测试运行后将其删除。
我遇到的问题是,模块级 JSON 的设置返回了一个值,该值是我也打算测试的程序的其他功能所需要的。
这是我的意思的一个例子:

import unittest
import myProg  

class TestProg(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # initialize() creates the JSON file
        myProg.initialize()
        f = myProg.initialize_storage()
        return f

    def test_prog_func(self):
        myProg.prog_func("test_key", "test_value", f)

f 是我其余功能所需的项目。 此代码无效。我正在寻找一种方法,使我能够从 setUpClass 中“return f”,以便在整个测试过程中使用。

最佳答案

你不能返回任何东西,不,返回值被忽略。您可以设置类属性,这些属性可用于所有测试:

class TestProg(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # initialize() creates the JSON file
        myProg.initialize()
        cls.f = myProg.initialize_storage()  # set a class attribute

    def test_prog_func(self):
        # self.f here will find the class attribute
        myProg.prog_func("test_key", "test_value", self.f)

那是因为对实例的属性查找也会找到类属性(毕竟这就是找到方法的方式)。

请注意,测试运行器将为每个正在运行的测试创建一个类的新实例;确保实例状态是干净的。类状态未清除,因此如果您更改测试中的类属性,您将不再具有适当的测试隔离。

关于python - unittest 的 setUpClass 类方法能否返回一个值以在其他测试中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46805200/

相关文章:

python - 有没有办法在 python 中的 KeyboardInterrupt 上永不退出?

python - 将 unicode 转换为日期时间 strptime python

swift - 单元测试函数 'XCTAssertEqualWithAccuracy' 在 Xcode Beta 5/Swift 4.0 中被弃用

python - 取消线程中的任务执行并从队列中删除任务

Java 相当于 Python 的 struct.pack?

python - 如何让 tkinter scale 小部件将其上限设置为更新的变量?

python - 使用递归查看随机列表时如何跟踪偶数的数量

python - 使用Python读取csv时指定换行符 ('\n' )

java - try-with-resource 单元测试覆盖率

android - 在 Android 单元测试中模拟 Environment.getExternalStorageDirectory()