推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
1800x
V2EX  ›  Python

如何 mock 一个异常,并抛出??

  •  
  •   1800x · May 9, 2019 · 6015 views
    This topic created in 2703 days ago, the information mentioned may be changed or developed.

    看下面的例子:

    class TestService(unittest.TestCase):
        def test_raise(self):
            class MyException(BaseException):
                pass
            
            mockedException = mock.create_autospec(spec=MyException, instance=True)
            self.assertIsInstance(mockedException, BaseException)
            raise mockedException
    

    输出:TypeError: exceptions must derive from BaseException 大意是:抛出的异常对象必须是继承自 BaseException

    在实际环境中,这个需要 mock 的异常类是一个抽象基类。我使其继承自 abc.ABC 和 Exception 当然,实际实现一个子类,然后在单元测试中使用这个子类,即可通过。但个人觉得这比较 low

    2 replies  •  2019-05-09 19:38:30 +08:00
    LeoQ
        1
    LeoQ  
       May 9, 2019 via iPhone
    这官方文档上都有啊, 用 side_effect

    https://docs.python.org/3/library/unittest.mock.html
    LeoQ
        2
    LeoQ  
       May 9, 2019 via iPhone
    还有 unittest 的文档 https://docs.python.org/3/library/unittest.html 一开头就举了个 asseetRaises 的例子
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2527 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 13:15 · PVG 21:15 · LAX 06:15 · JFK 09:15
    ♥ Do have faith in what you're doing.