繁体   English   中英

在 Python Try/Except 块中测试代码

[英]Testing a code in Python Try/Except Block

try:
    context.do_something()
except ValueError:
   return False

我确实测试了这个特定的代码。 当我使用副业时,例如

context = mock.MagicMoc()
context.do_something.side_effect = ValueError

当我使用 pytest.raises 时,测试通过但未测试代码。 我试过使用断言,但它失败了

有什么建议

我假设您将 try/except 代码包装在要测试的函数中。 这里有两个选项来测试这个。

1)在更改函数以重新引发 ValueError 之后,使用上下文管理器检查是否引发异常(尽管如果您不打算对它做任何事情,您最好不要首先捕获它):

from unittest import TestCase, mock

def do_something(c):
    try:
        c.do_something()
    except ValueError as e:
        raise e

class TestSomething(TestCase):
    def test_do_something(self):
        context = mock.MagicMock()

        context.do_something.side_effect = ValueError

        with self.assertRaises(ValueError):
            do_something(context)

2)在函数的成功控制路径中返回True,然后在测试中检查这个条件:

from unittest import TestCase, mock

def do_something(c):
    try:
        c.do_something()
        return True
    except ValueError as e:
        return False

class TestSomething(TestCase):
    def test_do_something(self):
        context = mock.MagicMock()

        context.do_something.side_effect = ValueError

        self.assertTrue(do_something(context))

暂无
暂无

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

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