Python, mock: raise exception

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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.

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

回答1:

I chanched

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

to

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

and removed the # <--- do not work line.

It's now working.

This is a good example.

EDIT:

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

also works.



回答2:

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:

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).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!