在 python 中使用 unittest 测试 class 初始值设定项

Testing class initializer using unittest in python

我正在使用 unittest 模块编写测试。 我需要使用不同的输入来测试测试用例中对象的初始化。 为此,我在 setUp() 中导入 class。但是当我尝试在 test_*() 函数中使用 class 时,我得到了这个错误 - NameError: name 'Example' is not defined

这是我的代码示例-

import unittest
class TestExample(unittest.TestCase):
    def setUp(self):
        import Example

    def test_sample_function(self):
        e = Example(1,2)

我知道我可以简单地在脚本顶部导入 class。但我不想那样做。我只需要在测试脚本设置期间导入它。 在这里寻求帮助。

import unittest
class TestExample(unittest.TestCase):
    def setUp(self):
        import Example
        self.Example = Example

    def test_sample_function(self):
        e = self.Example(1,2)

没有理由在 setUp 中导入模块。该模块在 sys.modules 中仍可全局使用,但您仅将其绑定到 本地 名称,该名称在 setUp returns 后消失。只需全局导入即可。

import unittest
import Example


class TestExample(unittest.TestCase):
    def test_sample_function(self):
        e = Example(1,2)