1、编写函数的测试用例
# 函数
def city_country(city,country,population=‘‘):
"""描述城市和所属国家"""
if population:
full_message = city + "," + country + " - population " + population
else:
full_message = city + "," + country
return full_message.title()
# TestCase
import unittest
from city_function import city_country
class CityTestCase(unittest.TestCase):
"""测试city_function.py"""
def test_city_country(self):
"""能够正确处理像Xian China 这样的城市名吗"""
city_message = city_country(‘xian‘,‘china‘)
self.assertEqual(city_message,‘Xian,China‘)
def test_city_country_population(self):
"""能够正确处理像Xian China -population 5000000 的值吗"""
city_message = city_country(‘xian‘,‘china‘,‘500000‘)
self.assertEqual(city_message,‘Xian,China - Population 500000‘)
unittest.main
2、编写类的测试用例
#类
class Employee():
"""创建一个雇员类"""
def __init__(self,first_name,givn_name,salary):
"""初始化雇员属性"""
self.first_name=first_name
self.givn_name=givn_name
self .salary=salary
def give_raise(self,incr_salary=5000):
"""增加年薪"""
self.salary+=incr_salary
return self.salary
#TestCase
import unittest
from employee_message import Employee
class TestEmployee(unittest.TestCase):
"""测试雇员类"""
def setUp(self):
"""使用setUp方法对类进行实例化"""
self.employee1 = Employee(‘du‘,‘gang‘,8000).give_raise()
self.employee2 = Employee(‘du‘, ‘gang‘, 8000).give_raise(2500)
def test_default(self):
"""工资自增方式"""
self.assertEqual(self.employee1,13000)
def test_incre(self):
"""工资自定义"""
self.assertEqual(self.employee2,10500)
unittest.main
3、unittest Module 中的断言方法
方法 |
用途 |
assertEqual(a,b) | 核实a==b |
assertNotEqual(a,b) | 核实a!=b |
assertTrue(x) | 核实x为True |
assertFlase(x) | 核实x为False |
assertIn(item,list) | 核实item在list中 |
assertNotIn(item,list) | 核实item不在list中 |
原文:https://www.cnblogs.com/startingpoint-fly/p/10674944.html