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
相关产品推荐
相关产品推荐

