How to make a mock object throw an exception in Google Mock?

user1735594 picture user1735594 · Jan 24, 2014 · Viewed 16k times · Source

With Google Mock 1.7.0, I have a mock object with a method, and I want to expect it to be called, and in this case the mocked method should throw an exception.

ObjectMock object_mock_;
EXPECT_CALL(object_mock_, method())
  .Times(1)
  .WillRepeatedly(???);

Is there a Google Mock action that throws an exception? I did not find it in the documentation, yet I doubt that nobody has needed it so far.

Thanks!

Answer

πάντα ῥεῖ picture πάντα ῥεῖ · Jan 24, 2014

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.