简体   繁体   English

如何测试是否使用单元测试引发和捕获了正确的异常?

[英]How to test if the right exception is raised and caught using unit testing?

I would like to test if a proper exception is raised and caught using unittest . 我想测试是否引发了一个适当的异常并使用unittest捕获。

Below is my sample code: 以下是我的示例代码:

def foo():
    try:
        raise Exception(ValueError)
    except ValueError:
        print "raised"

Here is what I would like to do: 这是我想做的事情:

self.assertRaises(ValueError, foo)

Since I caught the exception I'm not able to assertRaise the exception. 因为我发现了异常,所以我无法assertRaise异常。 Am I missing something or is there any other way? 我错过了什么或者还有其他方法吗?

My full code: 我的完整代码:

#!/usr/bin/python
import unittest
def foo():
    try:
        raise ValueError
    except ValueError, e:
        print "caught"
class tester(unittest.TestCase):
    def test1(self):
        with self.assertRaises(ValueError):
            foo()
    def test2(self):
        self.assertRaises(ValueError, foo)
if __name__ == '__main__':
    unittest.main()

No, you cannot test things that only have effects inside the function from outside of it. 不,你不能测试只在函数内部产生影响的东西。

What you can do is split the code that raises the exception into its own function, and then test that to check that the exception is raised (with assertRaises ). 你可以做的是将引发异常的代码拆分成它自己的函数,然后测试它以检查是否引发了异常(使用assertRaises )。 The original function can call that one, and if your normal tests on that work then apparently it catches the exception. 原始函数可以调用那个函数,如果对该函数进行正常测试,那么显然它会捕获异常。

However, whether that is a good idea depends on what your function does. 但是,这是否是一个好主意取决于你的功能。 Why does it matter that the function raises an exception at some point and then catches it? 为什么它很重要的功能,提出了在某些时候的异常,然后抓住它? Maybe one day you'll switch to some other way to do the same thing, with the same results. 也许有一天你会转而采用其他方式做同样的事情,结果相同。 Shouldn't your tests keep working then? 你的测试不应该继续工作吗?

If the exception thing is just an implementation detail, you probably shouldn't test it at all. 如果异常只是一个实现细节,你可能根本不应该测试它。

You can capture stdout and test for a string match. 您可以捕获stdout并测试字符串匹配。 Pytest offer a fixture for that. Pytest提供了一个夹具

#!/usr/bin/python
import unittest

def foo():
    try:
        raise ValueError
    except ValueError, e:
        print "caught"

def test_foo(capfd):
    foo()
    out, err = capfd.readouterr()
    assert out == "caught\n"

py.test test.py py.test test.py

============================= test session starts ==============================
platform linux2 -- Python 2.7.9 -- py-1.4.28 -- pytest-2.7.1
rootdir: /tmp, inifile: 
collected 1 items 

test.py .

=========================== 1 passed in 0.01 seconds ===========================

Try return True or False from your function. 尝试从函数返回TrueFalse

def foo():
    try:
        #work flow
        return True
    except ValueError:
        #error handle
        return False

self.assertFalse(foo())

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

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