Domanda

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!

È stato utile?

Soluzione

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.

Altri suggerimenti

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));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top