V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2019-05-09 16:57:39 +08:00 · 5037 次点击
    这是一个创建于 1785 天前的主题,其中的信息可能已经有所发展或是发生改变。

    看下面的例子:

    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 条回复    2019-05-09 19:38:30 +08:00
    LeoQ
        1
    LeoQ  
       2019-05-09 19:31:25 +08:00 via iPhone
    这官方文档上都有啊, 用 side_effect

    https://docs.python.org/3/library/unittest.mock.html
    LeoQ
        2
    LeoQ  
       2019-05-09 19:38:30 +08:00 via iPhone
    还有 unittest 的文档 https://docs.python.org/3/library/unittest.html 一开头就举了个 asseetRaises 的例子
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5287 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 09:31 · PVG 17:31 · LAX 02:31 · JFK 05:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.