How to mock method with optional parameter in Google Mock?

前端 未结 3 769
醉酒成梦
醉酒成梦 2021-02-18 21:30

How to mock a method with optional parameter in Google Mock? For example:

class A
{ 
public:
    void set_enable( bool enabled = true );
};

cl         


        
相关标签:
3条回答
  • 2021-02-18 21:42

    Some modifications to PiQuer's answer. You wouldn't need a wrapper if just add the name, "enabled" to the variable of type bool in your MOCK_METHOD1 like below:

    class A
    { 
        public:
        void set_enable( bool enabled = true );
    };
    
    class MockA : public A
    {
        MOCK_METHOD1( set_enable, void( bool enabled ) );
    };
    
    0 讨论(0)
  • 2021-02-18 21:46

    This is an alternative of Marko's answer: If you don't want to change your original code, just implement the helper in the mock class:

    class A
    { 
    public:
        virtual void set_enable( bool enabled = true );
    };
    
    class MockA : public A
    {
        MOCK_METHOD1( set_enable_impl, void( bool ) );
        virtual void set_enable( bool enabled = true )
        {
            set_enable_impl( enabled );
        {
    };
    

    You still have to expect calls of set_enable_impl in your tests, for example

    MockA mockA;
    EXPECT_CALL(mockA, set_enable_impl(true)).Times(Exactly(1));
    EXPECT_CALL(mockA, set_enable_impl(false)).Times(Exactly(1));
    
    0 讨论(0)
  • 2021-02-18 22:07

    Change implementation of your method set_enable to use a helper method, like this:

    void set_enable( bool enabled = true ) { set_enable_impl(enabled); }
    

    Now, in class MockA, create a mock method for set_enable_impl:

    MOCK_METHOD1( set_enable_impl, void( bool ) );
    

    Then, in your production code you simply use set_enable as you would in the first place, while in tests you can set expectations on method set_enable_impl:

    MockA mockA;
    EXPECT_CALL(mockA, set_enable_impl(_))...;
    

    An alternative would be to overload the method by having versions with one and zero parameters. It is up to you to determine which way works better for your case.

    0 讨论(0)
提交回复
热议问题