我知道我的问题是多余的,并且互联网上有很多答案,但是我尝试了所有建议的解决方案,但仍然无法解决问题。
我正在尝试将单元测试与python中的源代码分开。
所以我的目录如下:
HelloWorld
__init__.py
source
__init__.py
helloworld.py
test
__init__.py
test_helloworld.py
我的source / helloworld.py看起来像这样:
class HelloWorld:
def __init__(self):
self.message = 'Hello, World!'
我的test / test_helloworld.py看起来像这样:
import unittest
from source.helloworld import HelloWorld
class MyTestCase(unittest.TestCase):
def test_message(self):
hw = HelloWorld()
self.assertEqual(hw.message, 'Hello, World!')
if __name__ == '__main__':
unittest.main()
现在,当我在PyCharm中运行测试时,将两个目录(源和测试)都标记为Sources根目录后,我的测试将运行并说OK(代码通过了测试)
但是当我尝试从终端运行测试时,出现错误ModuleNotFoundError:没有名为'source'的模块
我似乎无法理解问题。我是否需要修改PYTHONPATH?那不是 init .py文件应该做什么?
答案 0 :(得分:1)
通过调用test/
中的脚本,除非您需要做更多的工作,否则实际上可以使它之外的所有内容都不可见。相反,移至HelloWorld/
并调用python -m test.test_helloworld
。