C++ Unit Testing: Stubs (not mocks)?

The only difference between a Mock and a Stub is that a Mock enforces behavior, while a Stub does not.

As far as I am aware, Google Mock's mocks are actually stubs by default. They only enforce behavior if you place assertions on the various methods.


I think the missing piece of the puzzle is that you don't have to set an expectation on a method and instead you can just set a default return value.

Mocks

All the discussion and examples in the "Google Mock for Dummies" is focused around setting expectations. Everything talks about using some code similar to the following:

EXPECT_CALL(turtle, PenDown())
      .Times(AtLeast(1));

Which is what you want for mocking, but for stubbing you don't have any expectations. After reading that intro I had no clue how to use googlemock for stubbing.

Stubs

ratkok's comment led me to find out how to set a default return value. Here's how to specify a return value for a mocked object but no expectation:

ON_CALL(foo, Sign(_))
      .WillByDefault(Return(-1));

https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#setting-the-default-actions-for-a-mock-method

It appears googlemock will issue a warning if you call a method that has no EXPECT_CALL. Apparently you can prevent this warning by using their NiceMock construct or you can just ignore it. Additionally it appears you can avoid the warning by using an expect instead (which I'm not sure if it's a good idea for stubs). From the Google Mock FAQ:

EXPECT_CALL(foo, Bar(_))
    .WillRepeatedly(...);

I believe that is exactly what I was trying to figure out.

Update

I can confirm this works. I wrote a unit test using google test along with googlemock and was able to stub out a method for a class using ON_CALL.