Python单元测试与测试发现

2024-04-24 13:55:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要做什么才能让python的unittest工作?我查看了官方文档,因此提出了一些问题,甚至尝试使用nose,但到目前为止没有任何效果。我做错什么了?

bash:~/path/to/project/src/tests$ ls -l
total 8
-rw-r--r-- 1 myuser myuser 342 Out 11 11:51 echo_test.py
-rw-r--r-- 1 myuser myuser  71 Out 11 11:28 __init__.py
bash:~/path/to/project/src/tests$ python -m unittest -v echo_test

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

OK
bash:~/path/to/project/src/tests$ python -m unittest discover

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

OK
bash:~/path/to/project/src/tests$ cat echo_test.py
import unittest

class EchoTest(unittest.TestCase):  
    def fooTest(self):
        self.assertTrue(1==1)

    def barTest(self):
        self.assertTrue(1==2)

#suite = unittest.TestLoader().loadTestsFromTestCase(TestEcho)
#unittest.TextTestRunner(verbosity=2).run(suite)

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

如您所见,测试根本没有运行,我也不知道为什么(因为我不是python程序员)。 仅供参考,我使用的是Python2.7,__init__.py是一个空文件。 有什么想法吗?


Tags: topathpytestechoselfsrcproject
3条回答

您需要将这些方法重命名为以单词“test”开头。

http://docs.python.org/library/unittest.html所示:

A testcase is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.

unittest.main()将运行以“test”开头的所有函数。所以你应该重新命名你的函数

class EchoTest(unittest.TestCase):  
    def testfoo(self):
        self.assertTrue(1==1)

    def testbar(self):
        self.assertTrue(1==2)

我想说的是,您不能像运行可执行的python文件一样运行python单元测试。例如,这就是我的问题:

python -m unittest ./TestMyPythonModule.py

... (stack trace) ...
ValueError: Empty module name

它失败了。

但是,这是有效的:

python -m unittest TestMyPythonModule

一开始很容易被忽视。

相关问题 更多 >