在Python中使用Unittest进行单元测试
例
让我们看一下单元测试框架的基本结构。
# importing unittest module
import unittest
# unittest will test all the methods whose name starts with 'test'
class SampleTest(unittest.TestCase):
# return True or False
def test(self):
self.assertTrue(True)
# running the test
unittest.main()输出结果
如果运行上面的程序,您将得到以下结果。
---------------------------------------------------------------------- Ran 1 test in 0.001s OK
2.测试字符串方法
现在,我们将使用样本测试用例来测试不同的字符串方法。请记住,方法名称必须以test开头。
让我们看一下我们要编写的每种方法的简要介绍。
test_string_equality
此方法测试两个字符串是否相等或不使用assertEqaul的方法unittest.TestCase生成。
test_string_case
此方法测试两个串情况下是否相等或不使用assertEqaul的方法unittest.TestCase生成。
test_is_string_upper
此方法测试字符串是否是在上壳体或不使用assertTrue和assertFalse方法unittest.TestCase生成。
输出结果
如果运行上面的代码,则如果所有测试用例都通过,您将得到以下结果。
... ---------------------------------------------------------------------- Ran 3 tests in 0.001s OK
输出结果
如果运行上述程序,则将得到以下结果。
======================================================================
FAIL: test_is_string_upper (__main__.TestingStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "p:/Python Work/Stopwatch/practice.py", line 21, in test_is_string_upper
self.assertTrue('TUTORIALSPOINt'.isupper())
AssertionError: False is not true
----------------------------------------------------------------------
Ran 3 tests in 0.016s
FAILED (failures=1)即使所有测试用例中有一个测试用例失败,我们也将失败消息。
结论
如果您对本教程有任何疑问,请在评论部分中提及。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短