samedi 6 juin 2015

How to mock delegate constructors?

I am new to Unit Testing in C++. I am supposed to write a Unit test for my code and I am using Google Mock for the same. I have gone through their turtle example. But I am still confused as to how to mock a delegated constructor.

I was asked to use a delegate constructor by a senior who advised that I should use a delegated constructor so that the unit tests call this to avoid creating objects and inject mocks instead.

Currently the main code looks something like this

BaseClass::BaseClass(SomeClassA* obj_a)
  : BaseClass(obj_a, MakeUnique<SomeClassB>()) {
}


BaseClass::BaseClass(SomeClassA* obj_a,std::unique_ptr<SomeClassB> obj_b)
  : a_obj(CHECK_IFNULL(obj_a)),
    b_obj(std::move(obj_b)) {
}

CHECK_IFNULL is a macro used to check for a null pointer.

Now in the Unit test I am supposed to mock the delegated constructor so that it does not create objects for SomeClassA and B and instead mocks it.

After reading the turtle tutorial, I tried this:

class BaseClass_Mock : public BaseClass {
  BaseClass_Mock(
      SomeClassA* obj_a,
      std::unique_ptr<SomeClassB> obj_b)
      : BaseClass(a_obj_mock, b_obj_mock) {

      }


    MOCK_METHOD2(Somefunction,
                 string(const string& name,
                        const string& type)); 
};

After trying to build this code, I got an error saying that a_obj_mock and b_obj_mock are undefined.

Now if I define them as - for ex:

SomeClassA *a_obj_mock and
SomeClassB *b_obj_mock

then I am creating a new object right? That would defeat the purpose of using a delegated constructor in the first place. So how do I mock the objects of SomeClassA and SomeClassB so that I can perform unit testing for functions of BaseClass without creating new objects.

Aucun commentaire:

Enregistrer un commentaire