Search code examples
c++stlgooglemockwstring

Matching std::wstring in googlemocks EXPECT_CALL


I have the mocked interface

// Interface
class MyInterface
{
    void get(const std::wstring& param) = 0;
}

// Mock interface
class MyInterfaceMock : public MyInterface
{
    MOCK_METHOD1(get, void(const std::wstring& param));
}

Exemplaric test method:

...
EXPECT_CALL(myInterfaceMock, L"hello");

When I compile it (vs2015) I get the message

error C2664: 'testing::internal::MockSpec...: cannot convert argument 1 from 'const wchar_t [6]' to 'const testing::Matcher &'

followed by the message: Reason: cannot convert from 'const wchar_t [7]' to 'const testing::Matcher'

When I use std::string instead std::wstring the everything works fine. Does anybody know why the std::wstring cannot be matched?


Solution

  • I guess you meant EXPECT_CALL(myInterfaceMock, get(L"hello"));

    You should write EXPECT_CALL(myInterfaceMock, get(std::wstring(L"hello"))); everything should work.

    The real question is why matcher from std::string accepts const char* as value. The answer is - because google-mock library supported this by intention - see code:

    template <>
    class GTEST_API_ Matcher<std::string>
        : public internal::MatcherBase<std::string> {
     public:
      Matcher() {}
    
      explicit Matcher(const MatcherInterface<const std::string&>* impl)
          : internal::MatcherBase<std::string>(impl) {}
      explicit Matcher(const MatcherInterface<std::string>* impl)
          : internal::MatcherBase<std::string>(impl) {}
    
      template <typename M, typename = typename std::remove_reference<
                                M>::type::is_gtest_matcher>
      Matcher(M&& m)  // NOLINT
          : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
    
      // Allows the user to write str instead of Eq(str) sometimes, where
      // str is a string object.
      Matcher(const std::string& s);  // NOLINT
    
      // Allows the user to write "foo" instead of Eq("foo") sometimes.
      Matcher(const char* s);  // NOLINT
    };
    

    There is no equivalent specialization of Matcher<T> for std::wstring. I advice you do not add one - because it might change in future - this is gmock implementation detail. Instead you might ask gmock developers to add support for wstring in the similar way as for string... BTW, I already addeded one.