The simplest way is to use side_effect
that accept either iterable, callable or Exception (class or instance)
Alternatively side_effect
can be an exception class or instance. In this case the exception will be raised when the mock is called.
As showed in Quick Guide you can use side_effect
to raise an exception simply by
>>> mock = Mock(side_effect=KeyError('foo'))
>>> mock()
Traceback (most recent call last):
...
KeyError: 'foo'
Moreover you can use list and Exception together in side_effect
assignment. So the simplest way to do what you need is something like this:
>>> m = Mock(side_effect=[1, KeyError("bar"), 3])
>>> m("a")
1
>>> m("b")
...
KeyError: 'bar'
>>> m("c")
3
An other way to do it can be use a callable to write the logic of how your mock should react. In this case you are free to chose if it based on arguments or your test's state.