Python uses UnitTest for unit testing

One, unit test:

  1. Role: used to check the correctness of a function, a class or a module
  2. Result: The unit test passed. It indicates that the function of the test is normal; the test fails, indicating that the function has a bug or the test condition is entered incorrectly

Two, unit test for the class

  1. Class code to be tested
#coding=utf-8
class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def GetName(self):
        return self.name
    def GetAge(self):
        return self.age
  1. Test code
#coding=utf-8
# 对类进行单元测试
import unittest
from UnitTestClass import Person
class Test(unittest.TestCase):
    def setUp(self) -> None:
        print("开始测试时自动调用")
    def tearDown(self) -> None:
        print("结束测试时自动调用")
    def testInit(self):
        PersonObj = Person("Tom",20)
        self.assertEqual(PersonObj.name,"Tom", "Name属性值有误")
        self.assertEqual(PersonObj.age,PersonObj.GetAge(),"age属性值有误")

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

>>>Ran 1 test in 0.014s
>>>
>>>OK
>>>开始测试时自动调用
>>>结束测试时自动调用
>>>
>>>进程已结束,退出代码0
  1. When the test code is running, it needs to be modified to run with Unittest

Three, unit test for the function

  1. Function code to be tested
#coding=utf-8
def MySum(a,b):
    return a + b
def MySub(a,b):
    return a - b
  1. Test code
#coding=utf-8
# 对函数进行单元测试
import unittest
from UnitTestFunc import UnitTestFunc
class Test(unittest.TestCase):
    def setUp(self) -> None:
        print("开始测试时自动调用")
    def tearDown(self) -> None:
        print("结束测试时自动调用")
    def testMySum1(self):
        self.assertEqual(UnitTestFunc.MySum(1, 2), 3, "加法有误")
    def testMySub(self):
        self.assertEqual(UnitTestFunc.MySub(2, 1), 1, "减法有误")

if __name__ == '__main__':
    unittest.main()
>>>Ran 2 tests in 0.004s
>>>
>>>OK
>>>开始测试时自动调用
>>>结束测试时自动调用
>>>开始测试时自动调用
>>>结束测试时自动调用
>>>
>>>进程已结束,退出代码0

Four, unit test for the function

#coding=utf-8
import doctest
# doctest模块可以提取注释中的代码执行
# doctest严格按照Python交互模式执行
def MySum(a,b):
    """
    Get the sum from a and b
    :param a: firstNum
    :param b: secondNum
    :return: sum
    注意有空格
    example
    >>> print(MySum(1,2))
    3
    """
    return a + b +b

print(MySum(2,3))
>>>5

# 进行文档测试,运行通过不会有结果
doctest.testmod()

Guess you like

Origin blog.csdn.net/zhuan_long/article/details/111640842