unit testing – Python, mock: raise exception

unit testing – Python, mock: raise exception

I changed

@patch(stdLib.StdObject, autospec=True)

to

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

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

Its now working.

This is a good example.

EDIT:

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

also works.

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

unit testing – Python, mock: raise exception

Leave a Reply

Your email address will not be published. Required fields are marked *