我正在使用 Python 3.6 和最新版本的 vscode。
我的文件夹结构:
/folder
/src
src.py
/tests
src_test.py
src.py:
class Addition:
def __init__(self, a, b):
self.a = a
self.b = b
def run(self):
return self.a + self.b
src_test.py:
import unittest
from ..src.addition import Addition
class TestAddition(unittest.TestCase):
def test_addition(self):
inst = Addition(5, 10)
res = inst.run()
self.assertEqual(res, 16)
if( __name__ == "main"):
unittest.main()
这是我的项目settings.json:
{
"python.testing.unittestArgs": [
"-v",
"-s",
".",
"-p",
"*_test.py"
],
"python.testing.pytestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.unittestEnabled": true
}
然后在项目根文件夹下:
python3 -m unittest tests/src_test.py
File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName
module = __import__(module_name)
ModuleNotFoundError: No module named 'tests.src_test'
最佳答案
您缺少 __init__.py
测试文件夹下的文件,并且您的模块的导入需要调整。__init__.py
允许 Python 在文件夹结构中向上并到达 src.py
模块(另一个 __init__.py
在 src 下会很好,但没有必要让 vscode 测试工作)。
这是一个工作文件夹结构:
.
├── src
│ └── src.py
└── tests
├── __init__.py
└── src_test.py
另外,更改 src.py 中的行:
from ..src.addition import Addition
from src.src import Addition
关于python-3.6 - 如何在vscode中为python unittest配置单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59462488/