为何Python程序仅在单元测试时抛出ModuleNotFoundError?
问题:运行单元测试时模块导入失败,单独运行代码却正常
项目结构
- project/source_code/constants.py
- project/source_code/calculator.py
- project/tests.py
constants.py 代码
# In 'constants.py' MIN_VALUE = 0 MAX_VALUE = 100
calculator.py 代码
# In 'calculator.py' import constants class Calculator: #Create initialiser (not used at the moment) def __init__(self): return def get_sum(self, number1, number2): return number1 + number2 def main(): calculator = Calculator() print(calculator.get_sum(10, 10)) return if __name__ == "__main__": main() print("") exit(0)
tests.py 代码
# In 'tests.py' import unittest import source_code.calculator as Calculator class Test_Calculator(unittest.TestCase): def setUp(self): self.calculator = Calculator() return def test_calculator(self, number1, number2, errorMessage): self.assertEqual(self.get_sum(number1, number2), expected_LBTT, errorMessage) return def main(self): test_calculator(10, 10, "The calculated sum is wrong.") return if __name__ == "__main__": unittest.main()
错误现象
单独运行calculator.py时一切正常,但运行tests.py或执行python -m unittest命令时,出现以下错误:
> ====================================================================== > **ERROR: tests (unittest.loader._FailedTest.tests) > **---------------------------------------------------------------------- > ImportError: Failed to import test module: tests > Traceback (most recent call last): > File "C:\Users\Home\AppData\Local\Programs\Python\Python311\Lib\unittest\loader.py", line 407, in _find_test_path > module = self._get_module_from_name(name) > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > File "C:\Users\Home\AppData\Local\Programs\Python\Python311\Lib\unittest\loader.py", line 350, in _get_module_from_name > __import__(name) > File "C:\Users\Home\Desktop\BJSS\project\tests.py", line 2, in <module> > import source_code.calculator as Calculator > File "C:\Users\Home\Desktop\BJSS\project\source_code\calculator.py", line 1, in <module> > import constants > ModuleNotFoundError: No module named 'constants' > > > ---------------------------------------------------------------------- > Ran 1 test in 0.000s > > FAILED (errors=1)
原因分析
两种运行方式的差异在于Python的模块搜索路径:
- 单独运行
calculator.py时,Python自动把当前文件所在的project/source_code/目录加入搜索路径,所以能直接找到同目录下的constants.py。 - 运行
tests.py或python -m unittest时,Python的搜索路径是project/目录(测试文件所在目录),此时source_code/下的constants.py不在搜索范围内,自然找不到。
解决方法
1. 修正calculator.py的导入语句
把calculator.py里的import constants改成相对导入或绝对导入:
- 相对导入(推荐,适用于同目录模块):
from . import constants
- 绝对导入(以project为根目录):
from source_code import constants
2. 确保运行时的工作目录正确
运行测试前,切换到project/目录的上级目录(比如BJSS/),然后用模块方式执行测试:
python -m project.tests
或者临时把project/目录加入Python环境变量PYTHONPATH:
Windows命令行:
set PYTHONPATH=C:\Users\Home\Desktop\BJSS\project
之后再运行测试命令。
3. 修复tests.py中的其他错误
除了导入问题,你的测试代码还有几个语法/逻辑错误,修正后才能正常运行:
# In 'tests.py' import unittest from source_code.calculator import Calculator class Test_Calculator(unittest.TestCase): def setUp(self): self.calculator = Calculator() # 测试方法必须以test_开头,且只能有self参数 def test_sum_calculation(self): # 调用实例的get_sum方法,且预期值要明确 self.assertEqual(self.calculator.get_sum(10, 10), 20, "The calculated sum is wrong.") if __name__ == "__main__": unittest.main()
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

