与进行函数测试类似。
不同之处在于:
在测试类中,通常定义setUp(self)函数,在其中生成一个“被测试类”的实例,并把该实例,作为测试类的成员,在该类的各个测试用例中使用。这样就不用为每个用例生成一次被测试类的实例。
举例说明,被测试代码如下,该代码被存储在文件employee_function.py中:
class Employee:
def __init__(self,name,age,salary,ifmarried,*abilities):
self.name = name
self.age = age
self.salary = salary
self.ifmarried = ifmarried
self.abilities = abilities
def show_basic_info(self):
info = f"name:{self.name} age:{self.age} salary:{self.salary}"
return info
def salary_increase(self,amount=5000):
self.salary += amount
def if_married(self):
return self.ifmarried
def if_has_the_ability(self,ability):
try:
self.abilities.index(ability)
return True
except:
return False
def show_abilities(self):
result = ''
for ability in self.abilities:
result += ability
result += '/'
return result
测试代码如下:
import unittest # unittest is the module used to do the test
from employee_function import Employee # get_formatted_name is the function needed to be test
class EmployeeTestCase(unittest.TestCase): # class used to do test
def setUp(self):
self.my_employee = Employee('Emiliy','33',150000,False,'Python','MySQL','JS')
def test_show_basic_info(self):
info = self.my_employee.show_basic_info()
self.assertEqual(info,'name:Emiliy age:33 salary:150000')
def test_salary_increase(self):
amount = 10000
self.my_employee.salary_increase(amount)
self.assertEqual(self.my_employee.salary,160000)
def test_if_married(self):
self.assertFalse(self.my_employee.if_married())
def test_if_has_the_ability_for_true(self):
ability = 'Python'
self.assertTrue(self.my_employee.if_has_the_ability(ability))
def test_if_has_the_ability_for_false(self):
ability = 'C++'
self.assertFalse(self.my_employee.if_has_the_ability(ability))
def test_show_abilities(self):
result = 'Python/MySQL/JS/C++/'
self.assertNotEqual(self.my_employee.show_abilities(),result)
def test_show_abilities_content(self):
ability_list = self.my_employee.show_abilities().split('/')
self.assertIn('Python',ability_list)
if __name__ == '__main__':
unittest.main()
在测试类 EmployeeTestCase 中一共包含8个函数。
第一个函数setUp(self)中包含此次测试所有用例需要用到的被测类实例:my_employee
剩余的每个函数都是一个测试用例,对应被测类中的一个功能函数。
这里用到的‘断言’种类有:
1)assertEqual(a,b)
2)assertFalse(x)
3)assertTrue(x)
4)assertNotEqual(a,b)
5)assertIn(item,list)