【Python+unintest实例学习】用assert断言测试计算器Calculator代码,再次熟悉TestSuite和TextTestRunner

文件名称:Calculator。一段用python编写的计算器Calculator代码

def add(x,y):
    return x + y
def sub(x,y):
    return x - y

文件名称:test36 。这是单元测试代码:测试用例代码

# _*_ coding: utf-8 _*_

from unittest import TestCase, main, skip
from Calculator import add, sub

x, y = 5, 3

class MyTestCase(TestCase):
    def setUp(self):
        pass

    def test_01(self):
        result1 = add(x, y)
        self.assertEqual(result1, 8, "add方法,执行结果不正确")
    def test_02(self):
        print('test-02')
# test_03的断言刻意写错了,让大家可以看看执行结果
    def test_03(self):
        result2 = sub(x, y)
        self.assertEqual(result2, 22, "sub方法,执行结果不正确")

    def tearDown(self):
        pass
if __name__ == '__main__':
    main()

这是测试套件的代码:

# _*_ coding: utf-8 _*_
from test36 import MyTestCase
from unittest import TestSuite, TextTestRunner
suite = TestSuite()

suite.addTest(MyTestCase('test_01'))
suite.addTest(MyTestCase('test_02'))
suite.addTest(MyTestCase('test_03'))

if __name__ == '__main__':
    runner = TextTestRunner()
    runner.run(suite)

执行结果:

.sF分别代表通过、忽略skip,错误Fail

.sF
======================================================================
FAIL: test_03 (test36.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".......\test36.py", line 21, in test_03
    self.assertEqual(result2, 22, "sub方法,执行结果不正确")
AssertionError: sub方法,执行结果不正确

----------------------------------------------------------------------
Ran 3 tests in 0.002s

FAILED (failures=1, skipped=1)

当开发人员修改了计算器Calculator的代码时,测试用例执行时就会报错,根据报错信息,测试人员就可以更新,或同步开发人员。

发布了94 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/woshiyigerenlaide/article/details/104117384
今日推荐