【问题标题】:Testing a code in Python Try/Except Block在 Python Try/Except 块中测试代码
【发布时间】:2020-02-13 09:40:40
【问题描述】:
try:
    context.do_something()
except ValueError:
   return False

我会测试这个特定的代码。当我使用侧面努力时,例如

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

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

任何建议

【问题讨论】:

    标签: python unit-testing try-except


    【解决方案1】:

    我假设您将 try/except 代码包装在要测试的函数中。这里有两种测试方法。

    1) 使用context manager 来检查是否引发了异常,在更改您的函数以重新引发 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))
    

    【讨论】:

      猜你喜欢
      • 2020-01-18
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 2019-06-26
      • 2015-02-27
      相关资源
      最近更新 更多