lundi 1 mai 2023

Mocking Overloaded method with Gmock

Greetings so i have an interface like below

class AInterface {
public:
    /// The different states the =A can be in
    enum class State {
        
        IDLE,
        ...
        BUSY
    };

    
    struct AMetadata {
    /**
     * Default constructor
     */
    AMetadata() = default;

    AMetadata(fooId, State state)
    : fooId(fooId)
    , state(state){}


    FooId = NONE;
    State state = State::IDLE;
    };

    /// Destructor.
    virtual ~AInterface() = default;

    virtual void onStateChanged(State state){}; // deprecated but still have to be here
    virtual void onStateChanged(const AMetadata& metadata){}; // i am adding this method
};

my mock class is defined like this

class MockObserver : public AInterface {
public:
    MOCK_METHOD1(onStateChanged, void(State state));
    MOCK_METHOD1(onStateChanged, void(const AMetadata& metadata));
};


// arg is passed to the matcher implicitly
// arg is the actual argument that the function was called with
MATCHER_P(AMetadataMatcher, expectedMetadata, "") {
    return arg.state == expectedMetadata.state;
}

Basically in the test code the implementation looks like this where the previous arg was State but now the arg have to be AMetadata

EXPECT_CALL(*m_mockObserver, onStateChanged(_)).Times(AnyNumber());

EXPECT_CALL(*m_mockObserver, onStateChanged(AState::BUSY))
            .WillOnce(Invoke([&](Ametadata metadata) {
                EXPECT_EQ(...,...);
            }));
EXPECT_CALL(*m_mockObserver, onStateChanged(AState::IdLE))
            .WillOnce(Invoke([&](Ametadata metadata) {
                EXPECT_EQ(...,...);
            }));

Compiling as is obviously i get compilation error

ATest.cpp:: error: call to member function 'gmock_onStateChanged' is ambiguous
    EXPECT_CALL(*m_mockObserver, onStateChanged(_).Times(AnyNumber()));

I tried ::testing::TypedEq and ::testing::An like below, i still get compilation error

EXPECT_CALL(*m_mockObserver, onStateChanged(::testing::TypedEq<const AMetadata&>(_))).Times(AnyNumber());

ATest.cpp:1288:49: error: no matching function for call to 'TypedEq' EXPECT_CALL(*m_mockObserver, onStateChanged(::testing::TypedEq<const AMetadata&>())).Times(AnyNumber());

i even tried custom matcher something like

AMetadata metadata;
metadata.state = IDLE;
EXPECT_CALL(*m_mockObserver, onStateChanged(AMatcher<const AMetadata&>(metadata)).Times(AnyNumber()));

but i am still getting error, so i am not sure what the best way to work with overloaded functions in gmock, basically i need to write calls where expect calls needs to work on values within a struct and i am in a situation where not only the overloaded method have the same name but same number of arguements as well, any guidance or code snippet would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire