单元测试:如果使用try-except,测试不会失败

问题描述 投票:1回答:1

我正在尝试执行失败后的操作;所以只有失败才能收集有关系统状态的信息。

到目前为止,我没有找到有效的解决方案。我确实尝试添加一个尝试 - 除了这个工作;但是我的测试运行输出是“成功”,这是完全错误的。

try:
    self.assertFalse(x>1, "the test failed")
except Exception as e:
    print(e)
    # do other post failure actions

由于异常被捕获,我假设单元测试类不会参与报告错误,最终导致测试没有失败。

如何将故障同时“升级”到except部分和Unit测试类?

python unit-testing python-unittest
1个回答
3
投票

捕获并记录异常后,您可以重新引发异常:

try:
    self.assertFalse(x>1, "the test failed")
except Exception as e:
    print(e)
    # do other post failure actions

    raise

请注意,您可能并且应该be more specific about the error you are catching - 在这种情况下,您正在寻找捕捉AssertionError exception而不是通用Exception

© www.soinside.com 2019 - 2024. All rights reserved.