猿问

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

我正在使用 unittest 模块来编写测试。我需要使用不同的输入来测试测试用例内对象的初始化。为此,我将在 setUp() 中导入该类。但是,当我尝试在 test_*() 函数中使用该类时,出现此错误 -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)

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


三国纷争
浏览 210回答 2
2回答

元芳怎么了

import unittestclass 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。只需在全球范围内导入即可。import unittestimport Exampleclass TestExample(unittest.TestCase):    def test_sample_function(self):        e = Example(1,2)
随时随地看视频慕课网APP

相关分类

Python
我要回答