Python,模拟:引发异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40736292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:56:12  来源:igfitidea点击:

Python, mock: raise exception

pythonunit-testingexceptionmocking

提问by user4780495

I'm having issues raising an exception from a function in my test:

我在测试中从函数中引发异常时遇到问题:

### Implemetation
def MethodToTest():
    myVar = StdObject()
    try:
        myVar.raiseError() # <--- here
        return True
    except Exception as e:
        # ... code to test
        return False

### Test file
@patch('stdLib.StdObject', autospec=True)
def test_MethodeToTest(self, mockedObjectConstructor):
    mockedObj = mockedObjectConstructor.return_value
    mockedObj.raiseError.side_effect = Exception('Test') # <--- do not work
    ret = MethodToTest()
    assert ret is False

I would like to raiseError()function to raise an error.

我想raiseError()函数来引发错误。

I found several examples on SO, but none that matched my need.

我在 SO 上找到了几个例子,但没有一个符合我的需要。

回答by user4780495

I changed

我变了

@patch('stdLib.StdObject', autospec=True)

to

@patch('stdLib.StdObject', **{'return_value.raiseError.side_effect': Exception()})

and removed the # <--- do not workline.

并删除了该# <--- do not work行。

It's now working.

它现在正在工作。

Thisis a good example.

是一个很好的例子。

EDIT:

编辑:

mockedObj.raiseError.side_effect = Mock(side_effect=Exception('Test'))

also works.

也有效。

回答by Jmons

Ok, your answer you provided is valid, but you changed how you did it (which is fine. To fix your original problem, you need to assign a function to side_effect, not the results or an object:

好的,您提供的答案是有效的,但是您更改了操作方式(这很好。要解决您原来的问题,您需要将函数分配给 side_effect,而不是结果或对象:

def my_side_effect():
    raise Exception("Test")

@patch('stdLib.StdObject', autospec=True)
def test_MethodeToTest(self, mockedObjectConstructor):
    mockedObj = mockedObjectConstructor.return_value
    mockedObj.raiseError.side_effect = my_side_effect # <- note no brackets, 
    ret = MethodToTest()
    assert ret is False

Hope that helps. Note, if the target method takes args, the side effect needs to take args as well (I believe).

希望有帮助。请注意,如果目标方法采用 args,则副作用也需要采用 args(我相信)。