mercredi 1 avril 2020

Dependency inject Abstract Class to Parent class, cannot test with concrete class as it is not of type Abstract Class

I have a Child Class which is the implementation of an abstract class.

class Child : public IChild
{
    public:
        Child()
        Func() override;
        ....
    private:
        int someVar
        ...
};

I have a Parent Class which requires a child to be constructed. It should own this child - thus the unique_ptr.

class Parent : public IParent
{
    public:
        Parent(unique_ptr<IChild>& child) : _child(std::move(child))
        CallFunc() { _child->Func(); }
    private:
        unique_ptr<IChild> _child;
};

I have a mock Child

class MockChild : public IChild
{
    public:
        MockChild();
        Func() override;
    private:
        int someVar
        ...
};

Now when it comes to testing

TEST(TestSet, TestingFuncIsCalledOnce)
{
    unique_ptr<IChild> mockChild = make_unique<MockChild>();
    auto& mockChildRef = *mockChild;

    EXPECT_CALL(mockChildRef, Func()).Times(1);  <-- this causes an error as IChild does not have a gmock_Func. It works if I make a unique_ptr<MockChild>

    Parent(mockChild);  <---- this takes a IChild ptr so I can't make a unique_ptr<MockChild>
    Parent.CallFunc();
}

So the question is, how do I keep the abstraction in my code by taking Interfaces/abstract classes as arguments, but also provide a mock that I can check functions are called on?

Aucun commentaire:

Enregistrer un commentaire