Python单元测试计数测试
问题描述
使用unittest是否可以有一个选项来统计测试总数、跳过的测试数量和运行次数。在运行之后,测试失败的次数(我知道可以在输出中看到)。我想把它转储到JSON中,如果我想通过编程实现的话那就太好了
谢谢
解决方案
经过多次尝试和错误,我终于让它正常工作了...
基于scoffey's answer。
希望它能有所帮助。
import unittest
class MyTest(unittest.TestCase):
currentResult = None # holds last result object passed to run method
@classmethod
def setResult(cls, amount, errors, failures, skipped):
cls.amount, cls.errors, cls.failures, cls.skipped =
amount, errors, failures, skipped
def tearDown(self):
amount = self.currentResult.testsRun
errors = self.currentResult.errors
failures = self.currentResult.failures
skipped = self.currentResult.skipped
self.setResult(amount, errors, failures, skipped)
@classmethod
def tearDownClass(cls):
print("
tests run: " + str(cls.amount))
print("errors: " + str(len(cls.errors)))
print("failures: " + str(len(cls.failures)))
print("success: " + str(cls.amount - len(cls.errors) - len(cls.failures)))
print("skipped: " + str(len(cls.skipped)))
def run(self, result=None):
self.currentResult = result # remember result for use in tearDown
unittest.TestCase.run(self, result) # call superclass run method
def testA(self):
self.assertTrue(True) # succeeds
def testB(self):
self.assertTrue(False) # fails
def testC(self):
self.assertTrue(1 + None is None) # raises TypeError
@unittest.skip("skip it") # skipped
def testD(self):
self.assertTrue("whatever")
if __name__ == '__main__':
unittest.main()
使用
运行脚本python test.py > result.txt
Result.txt:
tests run: 3
errors: 1
failures: 1
success: 1
skipped: 1
我不确定这是不是最好的方法,但它起作用了。Unittest模块好用,但很难掌握,现在我觉得自己对它知之甚少。
相关文章