11.1
city.py
def get_city(city,country):
return city.title() + ',' + country.title()
test_city.py
import unittest
from city import get_city
class CityTestCase(unittest.TestCase):
def test_city(self):
cityname = get_city('Changsha','China')
self.assertEqual(cityname,'Changsha,China')
unittest.main()
11.2
当pop必不可少时:
def get_city(city,country,population):
return city.title() + ',' + country.title()+ '-' + str(population)
当pop可以选择时:
def get_city(city,country,population=''):
if population:
return city.title() + ',' + country.title()+ '-' + str(population)
else:
return city.title() + ',' + country.title()
测试类
import unittest
from city import get_city
class CityTestCase(unittest.TestCase):
def test_city_country_population(self):
cityname = get_city('Changsha','China',100000)
self.assertEqual(cityname,'Changsha,China-100000')
unittest.main()
11-3
Employee.py
class Employee():
def __init__ (self,first_name, second_name, salary):
self.first_name = first_name
self.second_name = second_name
self.salary = salary
def give_raise(self,r = 5000):
self.salary = self.salary + r
TestEmployee.py
import unittest
from employee import Employee
class Testemployee(unittest.TestCase):
def setUp(self):
self.em = Employee('san','zhang',1000)
def test_give_default_raise(self):
self.em.give_raise()
self.assertEqual(self.em.salary,6000)
def test_give_custom_raise(self):
self.em.give_raise(1000)
self.assertEqual(self.em.salary,2000)
unittest.main()