[英]Is it possible to run all unit test?
我有兩個模塊,有兩個不同的類及其相應的測試類。
foo.py
------
class foo(object):
def fooMethod(self):
// smthg
bar.py
------
class bar(object):
def barMethod(self):
// smthg
fooTest.py
------
class fooTest(unittest.TestCase):
def fooMethodTest(self):
// smthg
barTest.py
------
class barTest(unittest.TestCase):
def barMethodTest(self):
// smthg
在任何測試和源模塊文件中,我刪除了if __name__ == "__main__":
因為增加了一致性並遵循面向對象的意識形態。
就像在Java單元測試中一樣,我正在尋找創建一個模塊來運行所有unittest。 例如,
runAllTest.py
-------------
class runAllTest(unittest.TestCase):
?????
if __name__ == "__main__":
?????
我尋找搜索引擎,但沒有找到任何教程或示例。 有可能這樣做嗎? 為什么? 或者怎么樣?
注意:我在windows機器上使用eclipse和pydev發行版。
您可以創建一個TestSuite
並在其中運行所有測試, if __name__ == '__main__'
塊:
import unittest
def create_suite():
test_suite = unittest.TestSuite()
test_suite.addTest(fooTest())
test_suite.addTest(barTest())
return test_suite
if __name__ == '__main__':
suite = create_suite()
runner=unittest.TextTestRunner()
runner.run(suite)
如果您不想手動創建測試用例,請查看此問題/答案 ,它基本上可以動態創建測試用例,或者使用unittest
模塊的一些功能,如測試發現功能和命令行選項。
在基於內置python unittest模塊運行單元測試時,在項目運行的根級別
python -m unittest discover <module_name>
對於上面的具體示例,運行就足夠了
python -m unittest discover .
我認為你要找的是TestLoader 。 有了這個,您可以加載特定的測試或模塊或加載給定目錄下的所有內容。 此外, 這篇文章還有一些使用TestSuite
實例的有用示例。
編輯:我通常在test.py中的代碼:
if not popts.tests:
suite = unittest.TestLoader().discover(os.path.dirname(__file__)+'/tests')
#print(suite._tests)
# Print outline
lg.info(' * Going for Interactive net tests = '+str(not tvars.NOINTERACTIVE))
# Run
unittest.TextTestRunner(verbosity=popts.verbosity).run(suite)
else:
lg.info(' * Running specific tests')
suite = unittest.TestSuite()
# Load standard tests
for t in popts.tests:
test = unittest.TestLoader().loadTestsFromName("tests."+t)
suite.addTest(test)
# Run
unittest.TextTestRunner(verbosity=popts.verbosity).run(suite)
有兩件事:
使用PyDev右鍵單擊Eclipse中的文件夾,然后選擇“Run as-> Python unit-test”。 這將運行該文件夾中的所有測試(測試文件和方法的名稱必須以“test_”開頭。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.