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

时间:2017-04-20 06:36:58

标签: python unit-testing python-unittest

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

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

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

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

我如何"升级"同时故障部分和单元测试类失败了吗?

1 个答案:

答案 0 :(得分: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