11-1:城市和国家
def cityandcountry(city,country):
outcome = city + ', '+country
return outcome.title()
import unittest
from city_functions import cityandcountry
class cityandcountry_test(unittest.TestCase):
def test_city_conutry(self):
cac = cityandcountry('santiago', 'chile')
self.assertEqual(cac, 'Santiago, Chile')
unittest.main()
11-2:人口数量
def cityandcountry(city,country,population = ''):
if population:
outcome = city.title() + ', '+country.title() + ' - ' + 'population ' + population
else:
outcome = city.title() + ', ' + country.title()
return outcome
import unittest
from city_functions import cityandcountry
class cityandcountry_test(unittest.TestCase):
def test_city_conutry(self):
cac = cityandcountry('santiago', 'chile')
self.assertEqual(cac, 'Santiago, Chile')
def test_city_country_population(self):
cacp = cityandcountry('santiago', 'chile', '5000000')
self.assertEqual(cacp, 'Santiago, Chile - population 5000000')
unittest.main()
第一次加入population实参后测试失败。
第二次将population设置为可选的后测试成功。
编写第二个测试函数,得到两个成功的测试样例。
11-3:雇员
class Employee():
def __init__(self, first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
def give_raise(self, add = ''):
if add:
self.salary += add
else:
self.salary += 5000
import unittest
from employee_fuc import Employee
class Testep(unittest.TestCase):
def setUp(self):
first_name = 'Kenny'
last_name = 'Cheng'
salary = 10000
self.myemployee = Employee(first_name, last_name, salary)
def test_give_default_raise(self):
self.myemployee.give_raise()
self.assertEqual(self.myemployee.salary, 15000)
def test_give_custom_raise(self):
self.myemployee.give_raise(1000)
self.assertEqual(self.myemployee.salary, 11000)
unittest.main()
如图,两个测试成功。