Question

How to mock out the CustomStream external dependency here with either gmock or gtest?

#include <mylib/common/CustomStream.h>

namespace sender {
    void Send(int p1){
        mylib::common::CustomStream stream;
        stream << p1;
    }
}
Was it helpful?

Solution

Make CustomStream inherit from a pure virtual interface. Then inject the test double as a dependency into the function. For example:

namespace mylib {
    namespace common {

        class OutputStream {
            virtual void Output(int value) = 0;
            OutputStream& operator<<(int value) { this->Output(value); return *this; }
        };

        class CustomStream : public OutputStream {
            virtual void Output(int value) { /*...*/ };
        };

    }
}

namespace sender {
    void Send(OutputStream& stream, int p1) {
        stream << p1;
    }
}

namespace tests {

    class MockOutputStream : public mylib::common::OutputStream {
        MOCK_METHOD1(Output, void (int value));
    };

    TEST(testcase) {
        MockOutputStream stream;
        EXPECT_CALL(stream, Output(2));
        sender::Send(stream, 2);
    }

}

But put each class in a separate header file, of course. And having a function ("Send") without a class is not a good idea either, but I am guessing that is a legacy. (Note: I did not try to compile this. It is Google Mock+Test-ish syntax.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top