Role: used to check the correctness of a function, a class or a module
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
Class code to be tested
#coding=utf-8classPerson():def__init__(self,name,age):
self.name = name
self.age = age
defGetName(self):return self.name
defGetAge(self):return self.age
Test code
#coding=utf-8# 对类进行单元测试import unittest
from UnitTestClass import Person
classTest(unittest.TestCase):defsetUp(self)->None:print("开始测试时自动调用")deftearDown(self)->None:print("结束测试时自动调用")deftestInit(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 in0.014s
>>>>>>OK
>>>开始测试时自动调用
>>>结束测试时自动调用
>>>>>>进程已结束,退出代码0
When the test code is running, it needs to be modified to run with Unittest
Three, unit test for the function
Function code to be tested
#coding=utf-8defMySum(a,b):return a + b
defMySub(a,b):return a - b
#coding=utf-8import doctest
# doctest模块可以提取注释中的代码执行# doctest严格按照Python交互模式执行defMySum(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()