相关疑难解决方法(0)

Python,mock:引发异常

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

### 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
Run Code Online (Sandbox Code Playgroud)

我想raiseError()发挥作用以引发错误.

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

python unit-testing exception mocking

15
推荐指数
2
解决办法
4万
查看次数

标签 统计

exception ×1

mocking ×1

python ×1

unit-testing ×1