例題11-1 城市和國家& 11-2 人口數量
描述:
編寫一個函數,它接受兩個形參:一個城市名和一個國家名。這個函數返回一個格式爲City, Country 的字符串,如Santiago, Chile 。將這個函數存儲在一個名爲city_functions.py的模塊中。創建一個名爲test_cities.py的程序,對剛編寫的函數進行測試(別忘了,你需要導入模塊unittest 以及要測試的函數)。編寫一個名爲test_city_country() 的方法,覈實使用類似於’santiago’ 和’chile’ 這樣的值來調用前述函數時,得到的字符串是正確的。運行test_cities.py ,確認測
試test_city_country() 通過了。
修改前面的函數,使其包含第三個必不可少的形參population ,並返回一個格式爲City, Country - population xxx 的字符串,如Santiago, Chile - population 5000000 。修改上述函數,將形參population 設置爲可選的。再次運行test_cities.py,確認測試test_city_country() 又通過了。再編寫一個名爲test_city_country_population() 的測試,覈實可以使用類似於’santiago’ 、’chile’ 和’population=5000000’ 這樣的值來調用這個函數。再次運行test_cities.py,確認測試test_city_country_population() 通過了。
代碼:
city_functions.py
def get_formatted_place(city, country, population = ''):
if population:
full_place = city.title() + ", " + country.title()
full_place += " - population " + population
else:
full_place = city.title() + ", " + country.title()
return full_place
test_cities.py
import unittest
from city_functions import get_formatted_place
class PlaceTestCase(unittest.TestCase):
def test_city_country(self):
full_place = get_formatted_place('santiago', 'chile')
self.assertEqual(full_place, 'Santiago, Chile')
def test_city_country_population(self):
full_place = get_formatted_place('santiago', 'chile', '5000')
self.assertEqual(full_place, 'Santiago, Chile - population 5000')
unittest.main()
結果:
例題11-3 僱員
描述:
編寫一個名爲Employee 的類,其方法init() 接受名、姓和年薪,並將它們都存儲在屬性中。編寫一個名爲give_raise() 的方法,它默認將年薪增加5000美元,但也能夠接受其他的年薪增加量。爲Employee 編寫一個測試用例,其中包含兩個測試方法:test_give_default_raise() 和test_give_custom_raise() 。使用方法setUp() ,以免在每個測試方法中都創建新的僱員實例。運行這個測試用例,確認兩個測試都通過了。
代碼:
employee.py
class Employee():
def __init__(self, first, last, salary):
self.first = first
self.last = last
self.salary = salary
def give_raise(self, increase = 50000):
self.salary += increase
test_employee.py
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
def setUp(self):
self.my_employee = Employee('Eric', 'Wong', 500000)
def test_give_default_raise(self):
self.my_employee.give_raise()
def test_give_custom_raise(self):
self.my_employee.give_raise(100000)
unittest.main()
結果:
發現的問題:
- 方法名必須以test_打頭,要傳參數self
- import unittest
- 編寫的類必須繼承
class NamesTestCase(unittest.TestCase):
from 程序名不用加py - unittest.main()別忘了,否則沒輸入
- 每完成一個單元測試,Python都打印一個字符:測試通過時打印一個句點;測試引發錯誤時打印一個E ;測試導致斷言失敗時打印一個F 。
- init也要傳遞self