关于Python中的代码测试

首先引入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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值