编写的代码需要测试是否有Bug
city_functions.py
def city_country(city, country):
return str(city) + ',' + str(country)
city_country_unittest.py
import unittest #导入测试模块
from city_functions import city_country as cc
class citytest(unittest.TestCase):
def test_city_country(self):
returnValue = cc("Santiago", "Chile")
self.assertEqual(returnValue, "Santiago,Chile") #运行结果是否和期待值相等
unittest.main() #运行测试
将city_functions.py中函数添加一个参数,测试程序不变
def city_country(city, country, population):
return str(city) + ',' + str(country) + " - " + "population " + str(population)
再对上面2个文件进行修改
def city_country(city, country, population = ''):
if not population:
return str(city) + ',' + str(country)
else:
return str(city) + ',' + str(country) + " - " + "population " + str(population)
import unittest
from city_functions import city_country as cc
class citytest(unittest.TestCase):
def test_city_country(self):
returnValue = cc("Santiago", "Chile")
self.assertEqual(returnValue, "Santiago,Chile") #运行结果是否和期待值相等
def test_city_country_population(self):
returnValue = cc("Santiago", "Chile", 5000000)
self.assertEqual(returnValue, "Santiago,Chile - population 5000000")
unittest.main() #运行测试
class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
print("Survey results:")
for response in self.responses:
print('- ' + response)
test_language_survey.py
import unittest
from survey import AnonymousSurvey
class testLanguageSurvey(unittest.TestCase):
def setUp(self): #创建的变量供后面测试函数用
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_response(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
unittest.main()
class Employee():
def __init__(self, firstname, lastname, salary):
self.firstname = firstname
self.lastname = lastname
self.salary = salary
def give_raise(self, raisedmoney = 5000):
self.salary += raisedmoney
test_employee.py
from employee import Employee
import unittest
class test_employee(unittest.TestCase):
def setUp(self) -> None:
self.employee_default = Employee('michael', 'ming', 5000)
self.employee_custom = Employee('kobe', 'bryant', 5000)
def test_dafault(self):
self.employee_default.give_raise()
self.assertEqual(10000, self.employee_default.salary)
def test_custom(self):
self.employee_custom.give_raise(1000)
self.assertEqual(6000, self.employee_custom.salary)
unittest.main()