0

Ok, I have a Base class and a MockBase. Code is attached below. I have managed to find a solution but not sure if it's the optimal.

class Base
{
  public :
    Base ( const int v ) ;
    bool check( const int );
    virtual bool getValue() { return _value ) ;
  private :
    bool _value;
}

implementation is here

Base::Base( const int v)
{
  _value = check( v ) ; // where check calls some legacy stuff and returns a bool
}

So - ideally I would like my MockBase to override this check function - which is called on construction. Doing something like this didn't work for me.

class MockBase : public Base
    {
      public :
        MockBase ( const int v ) ;
        MOCK_METHOD1( check, bool( const int ) ) ;
    }
 // TEST

MockBase base( 5 ) ;
EXPECT_CALL( base, checkLevel( 5 ) )
     .WillRepeatedly(Return( true ) ) ;
/// then testing getValue returns false

Why is that ? My current solution is on PS, but ideally I would like to know whether the above is valid approach or not ( and code is failing due to my bug and not because this is not possible at all).

My explanation is that, I think that when calling MockBase base( 5 ) ; the MockBase object calls the legacy check instead because the Base constructor is called.

PS :

To solve it, I had to provide a protected Base() constructor in my base class, which was used by MockBase and put my expect call on the getValue(). I can give code but the question is mostly on the above - if it can work like this.

ghostrider
  • 5,131
  • 14
  • 72
  • 120
  • You can't call `virtual` functions in a constructor body. – user0042 Sep 15 '17 at 10:51
  • Hmm good point - but this hasn't failed? So if I want to check my check function how can I do it? this is wrapper of a legacy function which I have no access to. – ghostrider Sep 15 '17 at 10:52
  • Possible duplicate of [Calling virtual functions inside constructors](https://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors) – user0042 Sep 15 '17 at 10:53
  • 1
    Check this [GMock and mocking constructors in a class with non virtual methods](https://stackoverflow.com/questions/6034031/gmock-and-mocking-constructors-in-a-class-with-non-virtual-methods) – Borislav Kostov Sep 15 '17 at 12:23

0 Answers0