6

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();
}
273K
  • 29,503
  • 10
  • 41
  • 64
peter55555
  • 1,413
  • 1
  • 19
  • 36

2 Answers2

9

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

DerKasper
  • 167
  • 2
  • 11
MIbrah
  • 1,007
  • 1
  • 9
  • 17
2

Generally I would simply return a string input stream which I have control over. That way I can push expected values into it. Along these lines:

std::istringstream myStream{"This is expected content"};
mocks::MyMockClass mockClass{myStream};

Then in your method:

std::istream& doTheMockedAction(){
    return myStream;
}

EDIT: For a mocking framework I would expect that you should be able to do something like this (bear in mind I haven't used Google Mocks so I am completely making this up)

auto mockOfRealType = MOCK_CLASS<RealType>();
EXPECT_CALL(mockOfRealType, doTheMockedAction()).WillOnce(ReturnRef(myStream))

ALSO: You need to assign it to a reference:

std::istream& a = doTheMockedAction();
Dennis
  • 3,683
  • 1
  • 21
  • 43
  • Thanks, your solution is ok. But I need to return different values. Is it possible to do something like that in inside WillOnce(...)' ? Just to return my std::istringstream` object? For example I want to return defined locally in test: std::istringstream xxx("xxx"). Is it possible? – peter55555 Mar 30 '16 at 12:21
  • 1
    @peter55555 I haven't used `gmock` so I can't say for certain but usually a mock framework will allow you to return any sub-class of the returned reference. So for example I would expect you should be allowed to do something along the lines of what I added to the main answer above (see edit) – Dennis Mar 30 '16 at 14:52
  • @downvoter it is common practise to leave a comment about what you think is wrong with the answer if you are down-voting. – Dennis Mar 31 '16 at 11:20