Search code examples
c++googletest

Using EXPECT_CALL for local methods


I know EXPECT_CALL is supposed to be used for mocked classes and their objects/methods. But is it ever possible to use this to expect calls of local methods?

void Sample::Init()
{
   // some codes here...

   auto enabled = isFeatureEnabled();

   //some other things here
}

bool Sample::isFeatureEnabled()
{
   return lights_ and sounds_;
}

I want to EXPECT_CALL isFeatureEnabled() - is this at all possible?


Solution

  • You can try this, I find this approach useful:

    class template_method_base {
    public:
      void execute(std::string s1, std::string s2) {
        delegate(s1 + s2);
      }
    
    private:
      virtual void delegate(std::string s) = 0;
    };
    
    class template_method_testable : public template_method_base {
    public:
      MOCK_METHOD1(delegate, void(std::string s));
    };
    
    TEST(TestingTemplateMethod, shouldDelegateCallFromExecute) {
      template_method_testable testable_obj{};
    
      EXPECT_CALL(testable_obj, delegate("AB"));
    
      testable_obj.execute("A", "B");
    }