我已经为一个函数编写了一个单元测试,但我似乎无法理解错误的含义。你知道吗
这是应用程序类
class ShoppingList(object):
cart = {} # A dictionary to hold item_name:price as key:value
balance = 0
budget_amount = 0 # one wouldn't want to shop for more than is available
def __init__(self, budget_amount):
self.budget_amount = budget_amount
# a method to add items to the cart dictionary
def addItem(self, item_name, price, quantity):
# declare arguement types and check they are use correctly
number_types = ( int, float, complex)
if isinstance(price, number_types) and isinstance(quantity, number_types) and isinstance(item_name, str):
self.cart[item_name] = price
total_cost = self.calculatePrice(price, quantity)
self.balance = self.budget_amount - total_cost
else:
raise ValueError
# a method to calculate total cost
def calculatePrice(self, price, quantity):
total_amount = price * quantity
#check total doesnt exceed balance we have
if total_amount > self.balance:
return("That amount is more than what we have")
return total_amount
我写下的单元测试描述如下。你知道吗
import unittest
from app.shoppinglist import ShoppingList
# a class to contain test cases for the shopping list
class ShoppingListTest( unittest.TestCase ):
def setUp(self):
budget_amount = 500
self.shoppingList = ShoppingList(budget_amount)
# method to test value types in addItem
def test_addItem_method_returns_error_for_nonInt(self):
self.assertRaises(ValueError, self.shoppingList.addItem, 1, "one", "thirty")
# method to check if quantity arg is not a number
def test_addItem_method_returns_error_for_quantityArg_string(self):
self.assertRaises( ValueError, self.shoppingList.addItem, "rice", "four", 400)
# method to check if price arg is not a number
def test_addItem_method_returns_error_for_priceArg_string(self):
self.assertRaises( ValueError, self.shoppingList.addItem, "Water", 4, "hundred")
# check if calculatePrice raises an error if total cost exceeds budget cost
def test_calculatePrice_returns_err_for_exceedingBudget(self):
result = self.shoppingList.calculatePrice( 2, 150)
self.assertGreaterEqual(self.shoppingList.balance, result)
当我运行测试时calculatePrice
总是返回错误type error '>=' not supported between instance of int and str
。我想达到的是确保calculatePrice中的总价不超过余额。如果确实引发错误,则通知用户
我将感谢任何人的帮助。谢谢
问题是,如果你买不到,总金额应该是0,而不是字符串。由于计算价格应始终返回数字
相关问题 更多 >
编程相关推荐