I'm just learning google test, I have a class
and I want to test its member function, below is the demo code:
class B {
//......
};
class A {
public:
//.....
void add (string s, B* ptrb) { m.insert(s, ptrb); }
void remove(string s) {
auto it = m.find(s);
if (it != m.end())
m.erase(it);
}
B* operator[](string s)
{
auto it = m.find(s);
if (it != m.end())
return (*it).second;
}
//.....
protected:
map<B*> m;
//.....
}
if I want to test add
like this:
class mygtest : public ::testing::Test
{
protected:
//....setup
//....teardown
A a;
};
TEST_F(mygtest, testadd)
{
B b1;
B b2;
a.add("1", &b1);
a.add("2", &b2);
//...how should i do next?
EXPECT_EQ(.....) //compare with who?
}
this is the first question.
the second question is:
In some conditions , I have to call another member function to get a value first , and use EXPECT_EQ
to test the current member function, how to test a function without using other member funtion? if it's necessary ?
CodePudding user response:
You have to just verify that state of A
has changed as desired.
So just check if it contains added objects.
TEST_F(mygtest, testadd)
{
B b1;
B b2;
a.add("1", &b1);
a.add("2", &b2);
EXPECT_EQ(a["1"], &b1);
EXPECT_EQ(a["2"], &b2);
EXPECT_EQ(a["3"], nullptr);
}
https://godbolt.org/z/ezrjdY6hh
Since there is not enough context it is impossible o improve this test (it doesn't look nice).
You can't avoid use of different functions. You are testing behavior of a class. So you are verify that other function do something else after state has been changed.
Do not event think to friend a test with production class. This is bad practice, since this will entangle test with implementation details. You will no be able refactor production code when test check implementation detail.
Here is small refactoring of test I usually do to improve how easy test is maintained: https://godbolt.org/z/Tc1n9Evzs