我正在使用 unittest 模块来编写测试。我需要使用不同的输入来测试测试用例内对象的初始化。为此,我将在 setUp() 中导入该类。但是,当我尝试在 test_*() 函数中使用该类时,出现此错误 -NameError: name 'Example' is not defined这是我的代码示例-import unittestclass TestExample(unittest.TestCase): def setUp(self): import Example def test_sample_function(self): e = Example(1,2)我知道我可以简单地在脚本顶部导入类。但我不想那样做。我只需要在测试脚本的设置期间导入它。在这里寻求帮助。
2 回答

元芳怎么了
TA贡献1798条经验 获得超7个赞
import unittest
class TestExample(unittest.TestCase):
def setUp(self):
import Example
self.Example = Example
def test_sample_function(self):
e = self.Example(1,2)

白猪掌柜的
TA贡献1893条经验 获得超10个赞
没有理由在setUp. 该模块在 中仍然全局可用sys.modules,但您只是将它绑定到返回后消失的本地名称setUp。只需在全球范围内导入即可。
import unittest
import Example
class TestExample(unittest.TestCase):
def test_sample_function(self):
e = Example(1,2)
添加回答
举报
0/150
提交
取消