python - 为什么我在 VS Code 中进行 Python 测试时得到 "No tests discovered"?

标签 python python-unittest

这是我的前几行代码,但我已经编码了 20 年,所以我很快就想运行单元测试。

我正在使用

  • Windows 10
  • VS Code 1.30.2 自 2019 年 1 月 7 日起。
  • Python 3.7.2
  • Python 扩展 ms-python.python 2018.12.1

这是我所在文件夹的内容。

    Directory: C:\DATA\Git\Py\my_first_code


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       19/01/2019     21:42                __pycache__
-a----       19/01/2019     21:35            289 messing.py
-a----       19/01/2019     21:42            204 test_messing.py
-a----       19/01/2019     22:07              0 __init__.py

据我所知,我并不在“venv”中。

这是test_messing.py的内容。

import unittest

class Test_Math(unittest.TestCase):
    def math_multiply__when__2_times_2__then__equals_4(self):
        self.assertEqual(2 * 2, 4)

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

__init__.py 是空的,我添加它是为了看看是否有帮助,messing.py 包含来自书中的 8 行代码。

当我尝试在 VS Code 中发现测试时,我得到了。

No tests discovered, please check the configuration settings for the tests. Source: Python (Extension)

更有趣的是,通过 Python 命令行运行测试发现看起来像这样。

PS C:\DATA\Git\Py\my_first_code> python -m unittest discover -v -s . -p test_*.py

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

最佳答案

正如 documentation 中所述对于 unittest 模块,您的测试方法名称需要以 test 开头。

tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.

例如

class TestMath(unittest.TestCase):
    def test_multiply(self):
        self.assertEqual(2 * 2, 4)

    def test_multiply_negative(self):
        self.assertEqual(-2 * -2, 4)
        self.assertEqual(2 * -2, -4)

    # etc...

请注意,这些都没有实际测试您的 messing.py 功能。为此,您需要导入messing,调用其上的函数,并断言这些函数返回的值是预期的。

最后,您应该遵循一些约定:

  • 使用简短的测试名称
  • 避免使用双下划线,因为它们通常在 Python 中引用“魔法”变量
  • 不要在每次测试中引用您正在测试的内容,因为套件本身已经按名称引用了它
  • 您的类名称不应包含下划线

关于python - 为什么我在 VS Code 中进行 Python 测试时得到 "No tests discovered"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54271900/

相关文章:

python - 如何正确模拟类(class)的私有(private)成员

python - 一种模拟松散定义的 Python dict 对象的简单方法

python - 如何在 REPL 中用 Python 运行单元测试?

python - setUpClass可以在unnitest框架中扩展吗?

python - 无法使用 PyQt4 中的 QProcess 放弃新进程的权限

python - pygame 主循环中的扭曲客户端?

python:无状态函数库设计

python - 如何从 Python 数组中删除值,对它们执行操作,然后将它们替换到原始数组中

python - 检查一个键是否存在并且它的值不是 Python 字典中的空字符串

python - 测试 Django 中的 Url 是否给出 500 错误