【发布时间】:2021-03-31 23:18:28
【问题描述】:
我在运行测试时不断收到 2 个错误。测试结果:test_details(测试汽车细节是否正确)和test_price_reduction(测试降价记录是否正确)
提前感谢您的帮助。
我正在测试这段代码:
import unittest
from car import Car
class TestCar(unittest.TestCase):
""" Tests for the Car class """
grade = 0
@classmethod
def setUpClass(cls):
""" Sets up the Test Case """
TestCar.grade = 0
print("Grading your Car class... ")
@classmethod
def tearDownClass(cls):
""" Tears down the Test Case """
print("Your grade for this part of the lab is: %d/8" % TestCar.grade)
def setUp(self):
""" Sets up the car objects to test in the subsequent tests """
self.car1 = Car("Honda", "Civic", 2015, 4999.99, 9999.99)
self.car2 = Car("Mazda", "Miata", 1990, 1500.0, 3999.88)
def test_constructor(self):
""" Tests that the car is successfully created """
self.assertIsNotNone(self.car1)
TestCar.grade += 1
self.assertIsNotNone(self.car2)
TestCar.grade += 1
def test_details(self):
""" Tests that the car details are correct """
self.assertEqual("2015 Honda Civic for sale for $9999.99", self.car1.get_details())
TestCar.grade += 1
self.assertEqual("1990 Mazda Miata for sale for $3999.88", self.car2.get_details())
TestCar.grade += 1
def test_profit(self):
""" Tests that the profit is calculated correctly """
self.assertEqual(self.car1.calc_profit(), 5000.0)
TestCar.grade += 1
self.assertEqual(self.car2.calc_profit(), 2499.88)
TestCar.grade += 1
def test_price_reduction(self):
""" Tests that the price reduction is recorded correctly """
self.car1.reduce_price(1000.50)
self.assertEqual(self.car1.calc_profit(), 3999.50)
TestCar.grade += 1
self.car2.reduce_price(999.88)
self.assertEqual(self.car2.calc_profit(), 1500.0)
TestCar.grade += 1
if __name__ == "__main__":
unittest.main()
使用此代码:
class Car:
""" Represents a car in a car lot """
def __init__(self, make, model, year, cost, price):
""" Initializes the car details """
self._make = make
self._model = model
self._year = year
self._cost = cost
self._price = price
def calc_profit(self):
""" Returns the projected profit """
return self._price - self._cost
def get_details(self):
print(f"{self._year} {self._make} {self._model} for sale for ${self._price}")
def reduce_price(self, reduction):
self._price = self._cost - reduction
car1 = Car('Honda', 'Civic', 2015, 5000.00, 9999.99)
car1.calc_profit()
car1.get_details()
car1.reduce_price(1000.50)
print(car1._price)
car2 = Car('Mazda', 'Miata', 1990, 2499.88, 3999.88)
car2.calc_profit()
car2.get_details()
car2.reduce_price(999.88)
print(car2._price)
def main():
pass
if __name__ == '__main__':
main()
这是我的输出:
2015 Honda Civic for sale for $9999.99
3999.5
1990 Mazda Miata for sale for $3999.88
1500.0
我在运行测试时不断收到 2 个错误。 测试结果:test_details(测试汽车细节是否正确) 和 test_price_reduction(测试降价记录是否正确)
提前感谢您的帮助。
【问题讨论】:
标签: python python-3.x function unit-testing python-unittest