Search code examples
c++namespacesgoogletestgooglemock

scope issue with DefaultValue from gmock


If I put the DefaultValue<int>::Set(10) in TEST, everything works fine, however, if I put it outside, it complains with error. What is wrong? the root cause?

using ::testing::DefaultValue;
struct Foo {
  MOCK_METHOD0(doWork, int());
};

DefaultValue<int>::Set(10); // error: specializing member 'testing::DefaultValue<int>::Set' requires 'template<>' syntax;

TEST(BarTest, DoesThis) {
  Foo foo;
  DefaultValue<int>::Set(10); // everything works fine.
  EXPECT_CALL(foo, doWork());
  foo.doWork();
}

Solution

  • DefaultValue<int>::Set(10) is a function call. It's a statement, and statements in general cannot appear on their own in namespace scope.

    Putting it in a function's scope is okay, and that's why it works. Though you may want to refactor it so it runs only once before you test suite (that's the point of having a global default value, after all).

    The error you get when you place it outside any function is just due to the compiler's confusion. Since it looks just like you are trying to specialize that member function of DefaultValue<int>, the compiler doesn't know your intent is to do something that cannot be done. So the diagnostic is phrased in a way that is meant to help you do a correct thing, if you made an honest mistake in specializing.