python - 如何在测试中导入被测试的模块?

标签 python unit-testing python-import

我是 Python 新手,有 Java 背景。

假设我正在开发一个带有包 hello 的 Python 项目:

hello_python/
  hello/
    hello.py
    __init__.py
  test/
    test_hello1.py
    test_hello2.py

我相信项目结构是正确的。

假设 hello.py 包含我想在测试中使用的函数 do_hello() 。如何在测试test_hello1.pytest_hello2.py中导入do_hello

最佳答案

您这里有 2 个小问题。首先,您从错误的目录运行测试命令,其次,您没有完全正确地构建项目。

通常,当我开发 python 项目时,我会尝试将所有内容都集中在项目的根目录上,在您的情况下,该根目录是 hello_python/ 。默认情况下,Python 在其加载路径上具有当前工作目录,因此如果您有这样的项目:

hello_python/
  hello/
    hello.py
    __init__.py
  test/
    test_hello1.py
    test_hello2.py


# hello/hello.py
def do_hello():
    return 'hello'

# test/test_hello.py
import unittest2
from hello.hello import do_hello

class HelloTest(unittest2.TestCase):
    def test_hello(self):
        self.assertEqual(do_hello(), 'hello')

if __name__ == '__main__':
    unittest2.main()

其次,test 现在不是一个模块,因为您错过了该目录中的__init__.py。您应该有一个如下所示的层次结构:

hello_python/
  hello/
    hello.py
    __init__.py
  test/
    __init__.py    #  <= This is what you were missing
    test_hello1.py
    test_hello2.py

当我在我的机器上尝试时,运行 python -m unittest test.hello_test 对我来说效果很好。

你可能会发现这还是有点麻烦。我强烈建议安装nose ,这将让您只需从项目的根目录调用 nosetests 即可自动查找并执行所有测试 - 前提是您拥有带有 __init__.py 的正确模块。

关于python - 如何在测试中导入被测试的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920141/

相关文章:

python - 如何阻止 Python 'import' 导入文件名?

python - 如何在不导入的情况下检查 Python 模块是否存在

python - 在 Python 环境中安装 Scrapy 包

python - 使用 LXML 返回标题文本

Python Numpy 数组修改

node.js - 测试express API需要本地服务器

python - 无法在 python 2.7.14 中导入任何模块(安装使用 pip)

python - 如何运行与python放置在不同文件夹中的shell脚本

unit-testing - 我应该打扰单元测试我的存储库层吗

java - 模拟被测试类中使用的不同类?