11-1城市和国家:
代码
函数:
def
city_country(
city,
country):
res
= city
+
"
,
"
+ country
return res
测试函数:
from test
import city_country
import unittest
class
City_countryTestCase(
unittest.
TestCase):
def
test_city_country(
self):
formatted
=
city_country
(
'
santiago
'
,
'
chile
'
)
self.
assertEqual
(formatted,
'
santiago,chile
'
)
unittest.
main
()
测试结果:
11-2 人口数量
函数:
def
city_country_population(
city,
country,
population):
res
= city
+
"
,
"
+ country
+
"
- population
"
+
str
(population)
return res
测试函数
from test
import city_country_population
import unittest
class
City_countryTestCase(
unittest.
TestCase):
def
test_city_country_population(
self):
formatted
=
city_country_population
(
'
santiago
'
,
'
chile
'
,
50000000
)
self.
assertEqual
(formatted,
'
santiago,chile - population 50000000
'
)
unittest.
main
()
测试结果:
11-3雇员
函数:
class
Employee():
def
__init__(
self,
last_name,
first_name,
annual_salary):
self.last_name
= last_name
self.first_name
= first_name
self.annual_salary
= annual_salary
def
give_raise(
self,
raise_amount
=
5000):
self.annual_salary
+= raise_amount
测试函数:
import unittest
from test
import Employee
class
TestEmployee(
unittest.
TestCase):
def
setUp(
self):
first_name
=
"
fn
"
last_name
=
"
ln
"
annual_salary
=
100000
self.myEmployee
=
Employee
(last_name, first_name, annual_salary)
def
test_give_default_raise(
self):
self.myEmployee.
give_raise
()
self.
assertEqual
(
self
.myEmployee.annual_salary,
105000
)
def
test_give_custom_raise(
self):
self.myEmployee.
give_raise
(
10000
)
self.
assertEqual
(
self
.myEmployee.annual_salary,
110000
)
unittest.
main
()
测试结果: