首先引入unittest的库:
import unittest
创建一个测试类:#carTestCase是类的名称,类的参数是unittest.case,这个类必须继承unittest.TestCase,这样子Python才能知道如何运行你编写的测试。
class carTestCase(unittest.TestCase):
在创建的类中定义测试函数,函数中利用了unittest类最有用的功能之一:断言方法,调用unittest中的assertEqual(),并向他传递两个参数进行比较。
def test_car(self):
formatted_car_name=my_used_car.get_descriptive_name()
self.assertEqual(formatted_car_name,‘2013 Sabaru Outback’)
unittest.main()
代码行unittest。main()让Python运行这个文件中的测试,运行之后结果如下:
.
Ran 1 test in 0.002s
OK
表示测试通过啦!
当天写的一部分代码在这里:
class Car():
def init(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def get_descriptive_name(self):
long_name=str(self.year)+’ ‘+self.make+’ '+self.model
return long_name.title()
def read_odometer(self):
print(“This car has”+str(self.odometer_reading)+“miles on it”)
print(str(self.odometer_reading))
my_new_car=Car(‘audi’,‘a4’,2016)
my_new_car.odometer_reading=23
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_used_car=Car(‘sabaru’,‘outback’,‘2013’)
print(my_used_car.get_descriptive_name())
import unittest
class carTestCase(unittest.TestCase):
def test_car(self):
formatted_car_name=my_used_car.get_descriptive_name()
self.assertEqual(formatted_car_name,‘2013 Sabaru Outback’)
unittest.main()