1、使用test_cities.py来测试city_function.py中的city_country函数
city_function.py文件内容
def city_country(city,country,population = 0):
"""返回一个形如'Santiago,Chile'的字符串"""
output_string = f"{city.title()}, {country.title()}"
if population:
output_string += f" - population {population}"
return output_string
test_cities.py文件内容
import unittest
from city_functions import city_country
class CitiesTestCase(unittest.TestCase):
"""测试city_functions.py"""
def test_city_country(self):
"""传入简单的城市和国家"""
santiago_chile = city_country('santiago','chile')
self.assertEqual(santiago_chile,'Santiago, Chile')
def test_city_country_population(self):
santiago_chile = city_country('santiago','chile',population = 5_000_000)
self.assertEqual(santiago_chile,'Santiago, Chile - population 5000000')
if __name__ == '__main__':
unittest.main()
测试结果:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
[Finished in 161ms]
2、使用test_employee.py测试employee.py中的类的功能
employee.py:
class Employee():
"""一个表示雇员的类"""
def __init__(self,f_name,l_name,salary):
"""初始化雇员"""
self.first = f_name.title()
self.last = l_name.title()
self.salary = salary
def give_raise(self,amount = 5000):
"""给雇员加薪"""
self.salary += amount
test_employee.py:
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
"""测试模块employee"""
def setUp(self):
"""创建一个Employee实例,以便在测试中使用"""
self.eric = Employee('eric','matthes',65_000)
def test_give_default_raise(self):
"""测试使用默认的年薪增加量是否可行。"""
self.eric.give_raise()
self.assertEqual(self.eric.salary,70000)
def test_give_custom_raise(self):
"""测试自定义年薪增加量是否可行。"""
self.eric.give_raise(10000)
self.assertEqual(self.eric.salary,75000)
if __name__ == '__main__':
unittest.main()
测试结果全部通过:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK