待测试函数,文件名为city_functions.py
#11-1城市和国家
'''输出城市名、国家、人口,人口参数可选'''
def city_country(city,country,population=''):
if population:
return (city +", " +country + "-population " + population)
else:
return(city +", " +country)
测试用例,文件名为test_cities.py
'''编写测试用例'''
#导入测试工具模块、待测试函数
import unittest
from city_functions import city_country
#编写一个继承unittest.TestCase的类,编写一系列方法对函数行为的不同方面进行测试
class NamesTestCase(unittest.TestCase):
#方法名必须以"test_"打头,这样才会在运行测试用例时,自动运行
def test_city_country(self):
'''若无人口实参值,测试函数能否正确运行'''
city_name=city_country("santiago","chile")
#unittest类的断言方法,核实预期结果与实际结果是否一致
self.assertEqual(city_name,"santiago, chile")
def test_city_country_population(self):
'''#若有人口实参值,测试函数能否正确运行'''
city_name=city_country("santiago","chile","500")
self.assertEqual(city_name,"santiago, chile-population 500")
unittest.main()