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

18,650

Solution 1

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.

Solution 2

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));
Share:
18,650

Related videos on Youtube

user1735594
Author by

user1735594

Updated on August 17, 2022

Comments

  • user1735594
    user1735594 over 1 year

    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!

  • user1735594
    user1735594 almost 10 years
    error: macro "ACTION_P" requires 2 arguments, but only 1 given
  • πάντα ῥεῖ
    πάντα ῥεῖ almost 10 years
    @user1735594 Sorry, indeed ACTION_P is intended to receive extra parameters, which aren't needed in your case. I'll edit my answer accordingly.
  • πάντα ῥεῖ
    πάντα ῥεῖ over 7 years
    I fairly don't get why this answer received a downvote? That can't have really something to do with it's content, but was probably meant personally.
  • Kyle Bridenstine
    Kyle Bridenstine almost 4 years
    Can you tell us what #include we need for Throw to work? It isn't found when I include #include <gmock/gmock.h> and #include <gtest/gtest.h>