You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

商店系统Unit Test Cases理应通过却全失败,求排查建议

商店系统单元测试全失败的排查建议

以下是针对你的测试用例全失败问题的具体排查步骤:

  • 先看具体报错信息
    不要只停留在"FAILED"状态,展开每个测试用例的错误详情。比如是断言不相等(AssertionError)、找不到对象(AttributeError)还是函数抛出了未预期的异常?这些细节是定位问题的关键。

  • 检查被测函数的输出方式
    确认welcome_to_shop和choose_item是返回字符串,还是直接用print输出。如果是后者,你的测试用例里result = welcome_to_shop(items)拿到的会是None,自然和预期字符串不匹配。这种情况要么修改业务函数让它返回结果,要么在测试里捕获标准输出(stdout)来验证。

  • 排查全局变量的污染问题
    你导入的money是全局变量,若某个测试用例修改了它的值(比如test_successful_purchase会扣钱),后续测试会用修改后的数据,导致断言失败。解决办法是在每个测试用例前重置money,或者用unittest的setUp方法初始化干净的测试环境:

    def setUp(self):
        global money
        money = 100  # 重置为初始余额
    
  • 核对参数传递顺序
    确认choose_item的函数定义参数顺序和你测试里的调用顺序一致。比如如果业务函数定义是def choose_item(item_name, items, money),但你调用的是choose_item(items, 'item2', money),参数顺序错误肯定会导致逻辑混乱。

  • 逐字符对比字符串断言
    字符串断言要求完全匹配,包括换行、空格、标点。比如你预期里的item3:£125,如果业务函数返回的是item3: £125(多了冒号后的空格),就会触发断言失败。可以在测试里打印result的值,和预期逐行对比,或者利用assertEqual报错里的差异提示定位问题。

  • 异常测试的正确性
    如果有测试余额不足抛出InsufficientFundsError的用例,必须用self.assertRaises上下文管理器来捕获异常,而不是直接调用函数。比如:

    def test_insufficient_funds(self):
        with self.assertRaises(InsufficientFundsError):
            choose_item(items, 'item3', money)
    

你提供的测试代码示例:

from unittest.mock import patch
from shop import InsufficientFundsError, items, money, welcome_to_shop, choose_item, choice

class TestShop(TestCase):
    def test_welcome_message(self):
        # Test if the display message appears
        result = welcome_to_shop(items)
        expected = "Welcome to our shop!\nHere are the items and their prices:\nitem1: £50\nitem2: £75\nitem3:£125"
        self.assertEqual(result, expected)

    def test_successful_purchase(self):
        # Test a successful purchase
        result = choose_item(items, 'item2', money)
        expected_output = "Here's your item2!\nYou now have £25 left.\nThank you for visiting our shop!"
        self.assertEqual(result, expected_output)

if __name__ == '__main__':
    main()

内容的提问来源于stack exchange,提问作者Angela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:00:37