Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a conversion operator int() using google mock

I have a class with following operator declared:

Foo::operator int() const
{
    return m_bar; // a private variable with type int of the class Foo
}

I want to mock class Foo but I have difficulties on this one. I looked up online and saw no solutions for conversion operators like int() in this case. Could anyone help please? Thank you.

like image 816
caiy Avatar asked Nov 21 '25 04:11

caiy


1 Answers

I'm not sure if there's a way to mock the conversion operator directly, but something along these lines would work:

class MockFoo : public Foo {
public:
    MOCK_CONST_METHOD0(conversionOperator, int());

    virtual operator int() const { return conversionOperator(); }
};

This would be used as you expect:

TEST(ConversionOperator, Returns42) {

    MockFoo f;
    EXPECT_CALL(f, conversionOperator()).WillOnce(Return(42));

    int value = f;
    ASSERT_EQ(42, value);
}
like image 149
Ian Avatar answered Nov 22 '25 17:11

Ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!