1、unittest Module中的断言方法
assertEqual(a,b) #核实a==b
assertNotEqual(a,b) #核实a!=b
assertTrue(x) #核实x为True
assertFalse(x) #核实x为False
assertIn(item,list) #核实item在list中
assertNotIn(item,list) #核实item不在list中
2、unittest.TestCase类中包含方法setUp(),若在TestCase类中包含了方法setUp(),Python将先运行它,再运行各个以test_打头的方法。这样,在哪个测试方法中都可使用方法setUp()中创建的对象了。
3、运行测试用例时,每完成一个单元测试,Python都打印一个字符:测试通过打印一个句点;测试引发错误打印一个E;测试导致断言失败打印一个F。
这就是运行测试用例时,在书的第一行看到的句点和字符数量各不相同的原因。如果测试用例包含很多单元测试,需要运行很长时间,就可通过观察这些结果来获悉有多少测试通过了。
练习
class Employee():
"""收集雇员姓名和年薪的类"""
def __init__(self,last_name,first_name,annual_salary):
self.last_name=last_name
self.first_name=first_name
self.annual_salary=annual_salary
def give_raise(self,up=5000):
self.annual_salary+=up
import unittest
from salary import Employee
class TestEmployee(unittest.TestCase):
def setUp(self):
self.annual_salary=100000
self.last_name='zh'
self.first_name='jw'
self.employee=Employee(self.last_name,
self.first_name,
self.annual_salary)
def test_give_default_raise(self):
self.employee.give_raise(0)
self.assertEqual(self.annual_salary,self.employee.annual_salary)
def test_give_custom_raise(self):
self.employee.give_raise()
self.assertEqual(self.annual_salary+5000,self.employee.annual_salary)
unittest.main()