c++testingmockinggooglemock

How to mock an external library in tests (httplib::Client )


Generally when writing unit tests, we create classes from interfaces and create mock classes for tests. e.g.

class TestedClass {

   TestedClass(std::shared_ptr<IDependency> dependency_ptr){...}

}

So it is easy to mock the dependency here by just inheriting from IDependency, like:

class MockDependency: public IDependency {
...
}

But how do we follow that approach for third party libraries? In this particular case, I am using httplib::Client. Since it is a concrete class from a thirdparty vendor, how can I mock that to test my own class which uses this class (injected via dependency injection)?


Solution

  • I doubt you are using every method httplib::Client can offer, so try to design your own interface that is enough for your application, e.g.:

    class IHttpClient {
    public:
        virtual ~IHttpClient() = default;
        virtual std::string get(std::string url) = 0;
        // more interfaces
    };
    

    Then your production implementation can be e.g. like this:

        std::string get(std::string url) override {
            httplib::Client cli(url);
            auto res = cli.Get("/hi");
            // error handling, maybe throw something
            return res->body;
        }
    

    and in the tests you can have

    ON_CALL(mockClient, get(matchingUrl)).WillByDefault(Return("expected reply"));