如何从模拟实例的方法中抛出异常?

问题描述 投票:0回答:2

我想测试的这个演示功能非常简单:

def is_email_deliverable(email):
    try:
        return external.verify(email)
    except Exception:
        logger.error("External failed failed")
        return False

这个函数使用了一个

external
服务,我想模拟它。

但是我不知道如何从

exception
抛出
external.verify(email)
,即如何强制执行
except
子句。

我的尝试:

@patch.object(other_module, 'external')
def test_is_email_deliverable(patched_external):    
    def my_side_effect(email):
        raise Exception("Test")

    patched_external.verify.side_effects = my_side_effect
    # Or,
    # patched_external.verify.side_effects = Exception("Test")
    # Or,
    # patched_external.verify.side_effects = Mock(side_effect=Exception("Test"))

    assert is_email_deliverable("[email protected]") == False

这个问题声称有答案,但它对我不起作用。

python exception python-unittest python-3.5 python-mock
2个回答
16
投票

您使用了

side_effects
而不是
side_effect
。 是这样的

@patch.object(Class, "attribute")
def foo(attribute):
    attribute.side_effect = Exception()
    # Other things can go here

顺便说一句,捕获所有

Exception
并根据它进行处理并不是一个好方法。


0
投票

您可以将

side_effect
值设置为
None

© www.soinside.com 2019 - 2024. All rights reserved.