close

[Solved] Python, mock: raise exception

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python, mock: raise exception in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Python, mock: raise exception Error Occurs?

Today I get the following error Python, mock: raise exception in python.

How To Solve Python, mock: raise exception Error ?

  1. How To Solve Python, mock: raise exception Error ?

    To Solve Python, mock: raise exception Error 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:

  2. Python, mock: raise exception

    To Solve Python, mock: raise exception Error 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:

Solution 1

I changed

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

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

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read