简体   繁体   English

如果引发异常,测试是否失败?

[英]Test that fails if exception is rised?

How to write a unit test that is considered failed if an exception is risen? 如果出现异常,如何编写被认为失败的单元测试?

I've found the assertRaises here but it seems to be doing the exact opposite. 我在这里找到assertRaises 但似乎正好相反。

Example from Django Django的范例

If something is wrong with the database the entry.save() will rises an exception. 如果数据库出了问题,则entry.save()将引发异常。

class TestModel(TestCase):
    def test_model_creation(self):
        try:
            entry = MyModel(name='Bob')
            entry.save()
        except Exception:
            self.assertEqual(0, 1)

The self.assertEqual(0, 1) is just a bad hack for the test to fail if there is an exception. self.assertEqual(0, 1)只是一个糟糕的技巧,如果存在异常,测试将失败。 What would be the right way of doing it? 正确的做法是什么?

No need to try and except. 无需尝试,除非。 If a test raises an error then it fails anyway. 如果测试引发错误,则无论如何都会失败。

Otherwise, see this post about the same thing . 否则,请参阅关于同一件事的这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM