Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 686
user1735594 Avatar asked Jan 24 '14 15:01

user1735594


People also ask

What is difference between On_call and Expect_call?

So use ON_CALL by default, and only use EXPECT_CALL when you actually intend to verify that the call is made.

What is gMock and Gtest?

In real system, these counterparts belong to the system itself. In the unit tests they are replaced with mocks. Gtest is a framework for unit testing. Gmock is a framework imitating the rest of your system during unit tests.

What is WillOnce in Gtest?

WillOnce(Return(x))" manipulates the expected value that it is always true. class Turtle { ... virtual int DoSomeMathTurtle(int , int); //Adds two ints together and returns them ... };

What is expect call in gMock?

In gMock we use the EXPECT_CALL() macro to set an expectation on a mock method. The general syntax is: EXPECT_CALL(mock_object, method(matchers)) . Times(cardinality) .


1 Answers

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.

like image 198
πάντα ῥεῖ Avatar answered Oct 07 '22 09:10

πάντα ῥεῖ