11-1 城市和国家:
代码:
homework.py
def city_fun(city, country):
return city.title()+", "+country
test_cities.py
import unittest
from homework import city_fun
class CityTestCase(unittest.TestCase):
def test_city_country(self):
formatted_string = city_fun("Santiago", "Chile")
self.assertEqual(formatted_string, "Santiago, Chile")
unittest.main()
输出:
11-2 人口数量
代码:
homework.py:
def city_fun(city, country, population):
return city.title()+", "+country + " - population " + str(population)
test_cities.py:
import unittest
from homework import city_fun
class CityTestCase(unittest.TestCase):
def test_city_country(self):
formatted_string = city_fun("Santiago", "Chile")
self.assertEqual(formatted_string, "Santiago, Chile")
unittest.main()
输出:
修改city_fun函数如下:
homework.py
def city_fun(city, country, population = None):
if population == None:
return city.title()+", "+country
return city.title()+", "+country + " - population " + str(population)
运行test_cities:
修改CityTestCase,增加一个测试函数如下:
import unittest
from homework import city_fun
class CityTestCase(unittest.TestCase):
def test_city_country(self):
formatted_string = city_fun("Santiago", "Chile")
self.assertEqual(formatted_string, "Santiago, Chile")
def test_city_country_population(self):
formatted_string = city_fun("Santiago", "Chile", population = 5000000)
self.assertEqual(formatted_string, "Santiago, Chile - population 5000000")
unittest.main()
运行test_cities.py
11-3 雇员
homework.py:
class Employee():
def __init__(self, first_name, last_name, annual_salary):
self.first_name = first_name
self.last_name = last_name
self.annual_salary = annual_salary
def give_raise(self, addition = 5000):
self.annual_salary += addition
Employee_test.py:
import unittest
from homework import Employee
class EmployeeTestCase(unittest.TestCase):
def setUp(self):
self.employee = Employee("Mark", "White", 2000)
def test_give_default_raise(self):
old = self.employee.annual_salary
self.employee.give_raise()
new = self.employee.annual_salary
self.assertEqual(new-old, 5000)
def test_give_custom_raise(self):
old = self.employee.annual_salary
self.employee.give_raise(10000)
new = self.employee.annual_salary
self.assertEqual(new-old, 10000)
unittest.main()
输出:
明明只有两个test,为什么会输出4个test呢……重开一次spyder再运行同样的代码,发现就显示ran 2 tests