I am doing a gtest. The function I would like to test takes two parameters.
int functionA(const ObjectA& obja, const stl::vector<ObjectB>& objb)
In my gtest, I would like to mock some test cases.
For obja
, what I did is:
ObjectA* obja = new ObjectA();
obja->type() = someValue; //setter function
obja->value() = someValue; // setter too
and then pass *(const_cast<ObjectA*>(obja))
as the parameter.
But for the vector, I am not sure what const
defines. I tried:
stl::vector<ObjectB*>* input;
ObjectB objb = new ObjectB();
objb->type() = someValue // setter
objb->id() = someValue//setter
input.push_back(objb);
then pass *(const_cast<ObjectB*>(input))
as the parameter.
But I get an error message saying "no matching function".
Could anyone tell me how I can mock input
and pass it in gtest?
For your convenience, the code in gtest is (assume class name is A):
ObjectA* obja = new ObjectA();
obja->type() = someValue; //setter function
obja->value() = someValue; // setter too
stl::vector<ObjectB*>* input;
ObjectB objb = new ObjectB();
objb->type() = someValue // setter
objb->id() = someValue//setter
input.push_back(objb);
A* instanceA = A::getInstance();
EXPECT_EQ(-2, instanceA->functionA(*(const_cast<ObjectA*>(obja)),*(const_cast<ObjectB*>(input)))) ;
I also tried not using const_cast
and pointers, I tried:
const ObjectA a;
a.type() = somevalue;
a.value() = somevalue;
const stl::vector<ObjectB> input;
ObjectB objb;
objb.type() = some;
input.push_back(objb);
and just pass input
and a
as parameters in test.
but I get an error saying "lvalue required as left operand of assignment" on a.type() = somevalue;
I think it is because there are two type()
in class ObjectA
, one is a setter without const
, one is a getter with const
. If I declare a
as const
, it believes type()
is the getter rather than the setter, so it cannot be a left-side value. That's why I want to use const_cast
.
Forget about const
, that's not the issue, The problem is the unnecessary and sometimes incorrect use of pointers.
Look at the declaration of the function you are testing.
int functionA(const ObjectA& obja, const stl::vector<ObjectB>& objb)
No pointers there. Now look at the declaration of the vector you are trying to pass to the function.
stl::vector<ObjectB*>* input;
That's (a pointer to) a vector of pointers, that's why the code doesn't work. The test function vector is not a vector of pointers. Here's how to write the code without any pointers.
ObjectA obja;
obja.type() = someValue; //setter function
obja.value() = someValue; // setter too
stl::vector<ObjectB> input;
ObjectB objb;
objb.type() = someValue // setter
objb.id() = someValue//setter
input.push_back(objb);
A* instanceA = A::getInstance();
EXPECT_EQ(-2, instanceA->functionA(obja, input));
Much easier.