mercredi 29 avril 2020

Mock for a concrete class using gmock in C++

I am stuck with creating a mock for a concrete class.

I know that is not a great idea to do this but I'm not not allowed to change production code.

My code is similar with:

Class A
{
public:
        A(B* b)
        {
                this->b = b;
        }
.........................
 void function_from_a_to_test(<arg>)
{
        if(!b)
                b->function_from_b();
        else
             //something to do
}
private:
        B * b;
};

class B
{
........
 public:       
        void function_from_b();
......
};
class MockB : public B , testing::Mock //i don't know why I can that, B is not virtual 
{

 MOCK_METHOD(function_from_b, void, (void));

};


A_Test :testing::Test{
 SetUp()
{
        b = new B();
        a = new A(b);
}

 TearDown()
{
        delete b ;
        delete a ;
}

void set_b(B * bb)
{
        a->b = bb;
}

.........................
}

In order to test I used Test_f

TEST_F(A_Test, Test_function_from_a_to_test)
{
//arrange

//act
 B * b_t = new MockB();
set_b(b_t);
EXPECT_CALL(*(static_cast<MockB> b_t), function_from_b))
        .Times(10);

function_from_a_to_test(arg);
}

It's seems that the test is passed but i got memory leak at static cast.

And If I store the result of static cast in another variable (in order to delete it), the expect call having that variable is failing.

I know that is not really a good practice, but I can not change the production code.

Has somebody a idea how to solve it? Or a better way to test this?

Aucun commentaire:

Enregistrer un commentaire