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

Python Unittest预期失败却显示通过,无异常抛出问题排查

测试用例预期失败却显示通过的问题解决

问题原因

你在测试方法里用try-except捕获了AssertionError,但捕获后没有重新抛出该异常。unittest的判定规则是:只有测试方法抛出未被捕获的断言异常(或其他未处理异常)时,才会标记测试失败。你把断言异常“吞”掉了,框架就误以为测试执行正常,所以输出ok。

代码问题点

看这段代码:

try:
    self.assertIn(
        expected_value,
        output,
        f"Could not find {expected_value} when ran command {command}.",
    )
    self.logger.info(f"{expected_value} found in command {command}")
except AssertionError as e:
    failure_message = f"Could not find {expected_value} when ran command {command}. Below is the output of the command:\n{output}"
    self.logger.error(failure_message)

断言失败触发AssertionError后,你只在日志里记录了错误,但没把异常抛出去。unittest完全不知道断言失败了,所以判定测试通过。

修复方法

在捕获异常并记录日志后,重新抛出异常,让unittest感知到断言失败:

try:
    self.assertIn(
        expected_value,
        output,
        f"Could not find {expected_value} when ran command {command}.",
    )
    self.logger.info(f"{expected_value} found in command {command}")
except AssertionError as e:
    failure_message = f"Could not find {expected_value} when ran command {command}. Below is the output of the command:\n{output}"
    self.logger.error(failure_message)
    raise  # 重新抛出捕获的AssertionError

这样一来,日志会记录错误信息,同时unittest会捕获到断言异常,把测试标记为失败状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:03:15