在 python 中编写单元测试时出现 ModuleNotFoundError

ModuleNotFoundError while writing unittest in python

这是我的项目结构

   |
   |---------src
   |          |
   |          |---------main.py
   |          |
   |
   |--------test
   |          |
   |          |---------__init__.py
   |          |
              |
              |---------test_main.py

这是我简单的主要内容class

main.py

def cli(cmd_arguments):
    ...

    
if __name__ == "__main__":
   ...
   cli(args)
    

这是测试方法

   test_main.py
            
   import unittest
   from argparse import Namespace
   import sys
            
   from project.src.main import cli
   sys.path.append('../src')
    
    class TestMainMethod(unittest.TestCase):
    
        def test_path_exception(self):
            with self.assertRaises(Exception):
                args = Namespace(method="abc", path='abcd')
                cli(args)

我正在尝试从 project 目录 运行 这个命令 python -m unittest 但出现异常 ModuleNotFoundError: No module named 'project.src'

project 不是包。这是你的项目根。

  1. __init__.py 添加到您的 src 文件夹(如果您还没有)。
  2. 使用from src.main import cli.
  3. 一般来说,您应该避免使用 sys.path.append('../src')。我不确定你为什么需要它。