用法:
side_effect
這可以是調用模擬時要調用的函數、可迭代的或要引發的異常(類或實例)。
如果你傳入一個函數,它將使用與模擬相同的參數調用,除非函數返回
DEFAULT
單例,否則對模擬的調用將返回函數返回的任何內容。如果函數返回DEFAULT
則模擬將返回其正常值(來自return_value
)。如果您傳入一個可迭代對象,則它用於檢索一個迭代器,該迭代器必須在每次調用時產生一個值。此值可以是要引發的異常實例,也可以是要從模擬調用返回的值(
DEFAULT
處理與函數案例相同)。引發異常的模擬示例(用於測試 API 的異常處理):
>>> mock = Mock() >>> mock.side_effect = Exception('Boom!') >>> mock() Traceback (most recent call last): ... Exception: Boom!
使用
side_effect
返回一係列值:>>> mock = Mock() >>> mock.side_effect = [3, 2, 1] >>> mock(), mock(), mock() (3, 2, 1)
使用可調用:
>>> mock = Mock(return_value=3) >>> def side_effect(*args, **kwargs): ... return DEFAULT ... >>> mock.side_effect = side_effect >>> mock() 3
side_effect
可以在構造函數中設置。下麵是一個示例,它將調用模擬的值加一並返回它:>>> side_effect = lambda value: value + 1 >>> mock = Mock(side_effect=side_effect) >>> mock(3) 4 >>> mock(-8) -7
將
side_effect
設置為None
會清除它:>>> m = Mock(side_effect=KeyError, return_value=3) >>> m() Traceback (most recent call last): ... KeyError >>> m.side_effect = None >>> m() 3
相關用法
- Python unittest.mock.Mock.reset_mock用法及代碼示例
- Python unittest.mock.Mock.__class__用法及代碼示例
- Python unittest.mock.Mock.call_args用法及代碼示例
- Python unittest.mock.Mock.method_calls用法及代碼示例
- Python unittest.mock.Mock.call_args_list用法及代碼示例
- Python unittest.mock.Mock.assert_called用法及代碼示例
- Python unittest.mock.Mock.assert_not_called用法及代碼示例
- Python unittest.mock.Mock.mock_calls用法及代碼示例
- Python unittest.mock.Mock.assert_has_calls用法及代碼示例
- Python unittest.mock.Mock.configure_mock用法及代碼示例
- Python unittest.mock.Mock.called用法及代碼示例
- Python unittest.mock.Mock.assert_called_once_with用法及代碼示例
- Python unittest.mock.Mock.assert_called_once用法及代碼示例
- Python unittest.mock.Mock.assert_any_call用法及代碼示例
- Python unittest.mock.Mock.call_count用法及代碼示例
- Python unittest.mock.Mock.assert_called_with用法及代碼示例
- Python unittest.mock.Mock.return_value用法及代碼示例
- Python unittest.mock.AsyncMock.assert_awaited_once_with用法及代碼示例
- Python unittest.mock.call用法及代碼示例
- Python unittest.mock.AsyncMock.assert_any_await用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 unittest.mock.Mock.side_effect。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。