How to make a mock object throw an exception in Google Mock?
The syntax for this is Throw(exception)
, where exception is any copyable value.
ObjectMock object_mock_;
EXPECT_CALL(object_mock_, method())
.Times(1)
.WillRepeatedly(Throw(exception));
Just write a simple action that throws an exception:
ACTION(MyThrowException)
{
throw MyException();
}
And use it as you would do with any standard action:
ObjectMock object_mock_;
EXPECT_CALL(object_mock_, method())
.Times(1)
.WillRepeatedly(MyThrowException());
There's also a googlemock standard action Throw()
, that supports throwing exceptions as action taken (Note that MyException
must be a copyable class, to get this working!):
ObjectMock object_mock_;
EXPECT_CALL(object_mock_, method())
.Times(1)
.WillRepeatedly(Throw(MyException()));
Find the full documentation for ACTION
and parametrized ACTION_P<n>
definitions in the GoogleMock CookBook.