How to mock method returning istream&?
Asked Answered
G

2

7

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();
}
Gryphon answered 30/3, 2016 at 11:51 Comment(4)
How are you assigning the returned value?Bookerbookie
Tell it its pants are out of fashion. Can you show what you tried, and what went wrong, in a minimal reproducible example?Marra
What exactly the problem you are having? I am assuming compilation error, because in google mock you can't use Return() for referencesViscardi
can you also add the details of 'sut' object.Viscardi
V
12

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

Viscardi answered 30/3, 2016 at 14:58 Comment(0)
P
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();
Pulmonary answered 30/3, 2016 at 12:1 Comment(3)
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?Gryphon
@Gryphon 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)Pulmonary
@downvoter it is common practise to leave a comment about what you think is wrong with the answer if you are down-voting.Pulmonary

© 2022 - 2024 — McMap. All rights reserved.