如何在python unittest中运行单个测试

时间:2014-04-30 15:05:33

标签: python python-unittest

许多标准库不使用类名,如何从命令行运行单个测试用例或将其添加到测试套件中?

此处提出了类似的问题,但所有解决方案都假设测试用例位于具有有效类名的文件中。

Running single test from unittest.TestCase via command line

1 个答案:

答案 0 :(得分:1)

简单方法,安装nosetest

nosetests -mtestAcosh /home/jamie/Downloads/Python-2.6.5/Lib/test/test_math.py

复杂的方法,将测试文件作为模块加载,然后使用args运行unittest.main

PYTHONPATH=/home/jamie/Downloads/Python-2.6.5/Lib/test python -c'from test_math import MathTests
import unittest
unittest.main(None,None,["","test_math.MathTests.testAcosh"])
'

我碰巧有test_math.py的版本没有unittest.main() 编写简单unittest文件的常用方法是添加

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

当这是单元测试文件的设置方式时,通常可以按照本答案中的描述进行单独的测试

Running single test from unittest.TestCase via command line

即,只需将“testClassName.test_iwanttorun”作为命令行arg