Warm tip: This article is reproduced from serverfault.com, please click

其他-Python单元测试模块抛出“ ModuleNotFoundError:没有名为'tests.test_file'的模块”

(其他 - Python Unit test module throws "ModuleNotFoundError: No module named 'tests.test_file'")

发布于 2019-06-26 21:06:11

我正在尝试为我一直在从事的项目执行测试用例。我过去曾经成功地执行过单元测试,但现在却出错了。我肯定知道没有任何库的更新或Path中的更改。我想查看源代码并弄清楚为什么会出错,但是还没有运气。任何帮助,将不胜感激。

Python版本-3.7.1

下面的示例代码

import unittest

class MyTestCase(unittest.TestCase):

def test_dummy(self):
    self.assertEqual(2+2,4)

我在cmd中使用了以下命令来执行测试。

C:\ Users \ Yadada \ Desktop \ repo \ mwe \ mwe> python -m unittest tests \ test_file.py'''

我的文件夹结构是

 MWE -|
      |_tests - |
                |_test_file.py

预期的输出是测试成功执行,因为它是直接的测试。但我最终收到以下错误

strclass
ERROR: test_file (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_file
Traceback (most recent call last):
  File "C:\Users\yadada\AppData\Local\Continuum\anaconda3\lib\unittest\loader.py", line 156, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'tests.test_file'


----------------------------------------------------------------------
Ran 1 test in 0.001s
Questioner
Bee
Viewed
11
Bee 2021-02-06 04:21:31

将空__init__.py文件放入测试文件夹后,该问题得到解决

有关其为何有效的更好解释,请参阅__init__.py的作用是什么?

谢谢@aws_apprentice的帮助。