c++c++11googlemockistream

How to mock method returning istream&?


I have mocked virtual method returning istream&. I'd like to use it in a testcase. How to return some value?

The problem is that istream is noncopyable.

I try something like this:

TEST(x, y)
{
     MockClass mock;
     std::istringstream str("Some text");

     EXPECT_CALL(mock, m(_)).WillOnce(Return(str)); // m method returns std::istream&

     sut.callMethod();
}

Solution

  • You should use ReturnRef() instead of Return(). Refer to gmock cheat sheet:

    https://github.com/google/googletest/blob/master/docs/gmock_cheat_sheet.md#returning-a-value