如何在未实现calculate_item_total_price时让Python前置测试正常运行?
问题描述
我需要在实现calculate_item_total_price函数前编写前置测试,当前测试代码如下:
def test(expected_discount: float = 0.3) -> tuple[bool, str]: item = Item("Item 1", 1, 1.0, expected_discount) total_price = item.calculate_item_total_price() actual_discount = round(1.0 - (total_price / (item.unit_price * item.quantity)), 2) fail_case = actual_discount != expected_discount if fail_case: return (False, f"Error in test_calculate_item_price_converts_discount: Incorrect discount\n - Expected: {expected_discount}\n - Actual: {actual_discount}") else: return (True, "Item.calculate_item_price correctly converts discount_percent to discount")
该函数尚未实现,调用时返回None,导致测试出现NoneType错误。请问如何在不实现该函数的前提下让测试正常运行?
解决方案
方法1:用Mock模拟方法返回值
利用Python标准库unittest.mock.patch直接模拟calculate_item_total_price的返回值,让它输出符合预期折扣逻辑的总价,测试就能正常执行:
from unittest.mock import patch def test(expected_discount: float = 0.3) -> tuple[bool, str]: # 计算预期总价:原价 * 数量 * (1 - 折扣率) expected_total = 1.0 * 1 * (1 - expected_discount) with patch.object(Item, 'calculate_item_total_price', return_value=expected_total): item = Item("Item 1", 1, 1.0, expected_discount) total_price = item.calculate_item_total_price() actual_discount = round(1.0 - (total_price / (item.unit_price * item.quantity)), 2) fail_case = actual_discount != expected_discount if fail_case: return (False, f"Error in test_calculate_item_price_converts_discount: Incorrect discount\n - Expected: {expected_discount}\n - Actual: {actual_discount}") else: return (True, "Item.calculate_item_price correctly converts discount_percent to discount")
方法2:添加临时占位实现
在Item类中给calculate_item_total_price写一个临时的占位方法,返回符合折扣逻辑的预期值,后续再替换为真实业务代码:
class Item: def __init__(self, name, quantity, unit_price, discount): self.name = name self.quantity = quantity self.unit_price = unit_price self.discount = discount # 临时占位,后续替换为真实逻辑 def calculate_item_total_price(self): return self.unit_price * self.quantity * (1 - self.discount)
方法3:在测试中增加None值检查
如果只是想避免报错,先验证函数状态,可以在测试里先判断total_price是否为None,提前返回结果:
def test(expected_discount: float = 0.3) -> tuple[bool, str]: item = Item("Item 1", 1, 1.0, expected_discount) total_price = item.calculate_item_total_price() # 先检查函数是否未实现返回None if total_price is None: return (False, "Error: calculate_item_total_price尚未实现,返回None") actual_discount = round(1.0 - (total_price / (item.unit_price * item.quantity)), 2) fail_case = actual_discount != expected_discount if fail_case: return (False, f"Error in test_calculate_item_price_converts_discount: Incorrect discount\n - Expected: {expected_discount}\n - Actual: {actual_discount}") else: return (True, "Item.calculate_item_price correctly converts discount_percent to discount")
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

