How to resolve "ValueError: Empty module name"?

How to resolve "ValueError: Empty module name"?

在我的 UnitTest 目录中,我有两个文件,mymath.pytest_mymath.py

mymath.py 文件:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(numerator, denominator):
    return float(numerator) / denominator

test_mymath.py 文件是:

import mymath
import unittest

class TestAdd(unittest.TestCase):
    """
    Test the add function from the mymath library
    """

    def test_add_integer(self):
        """
        Test that the addition of two integers returns the correct total
        """
        result = mymath.add(1, 2)
        self.assertEqual(result, 3)

    def test_add_floats(self):
        """
        Test that the addition of two integers returns the correct total
        """
        result = mymath.add(10.5, 2)
        self.assertEqual(result, 12.5)

    def test_add_strings(self):
        """
        Test that the addition of two strings returns the two strings as one
        concatenated string
        """
        result = mymath.add('abc', 'def')
        self.assertEqual(result, 'abcdef')

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

当我运行命令

python .\test_mymath.py

我得到了结果

Ran 3 tests in 0.000s

OK

但是当我尝试运行测试时使用

python -m unittest .\test_mymath.py

我收到错误消息

ValueError: Empty module name

回溯:

文件夹结构:

我正在关注这个article

我的 python 版本是 Python 3.6.6,我在本地机器上使用 windows 10。

使用python -m unittest test_mymath

你差不多明白了。而不是:

python -m unittest ./test_mymath.py

不要添加 ./ 所以你现在有:

python -m unittest test_mymath.py

您的单元测试现在应该 运行。