Here is my function I want to test:
template<typename T>
void free_items(std::vector<T*>& items)
{
std::for_each(items.begin(), items.end(), [](T* (&item)){delete item; item = nullptr; });
}
I expect the each pointer in my result vector will be freed and be set null correctly. So I write down the following test code.
This is my mock class:
struct FreeItemMock
{
FreeItemMock(bool& destroyed):m_destroyed (destroyed) {}
~FreeItemMock(){ m_destroyed = true;}
bool& m_destroyed ;
};
Here is my test code:
BOOST_AUTO_TEST_CASE(test_free_items)
{
bool destroyed[3] = {};
std::vector<FreeItemMock*> mocks;
mocks.push_back(new FreeItemMock(destroyed[0]));
mocks.push_back(new FreeItemMock(destroyed[1]));
mocks.push_back(new FreeItemMock(destroyed[2]));
BOOST_CHECK_EQUAL(destroyed[0], false);
BOOST_CHECK_EQUAL(destroyed[1], false);
BOOST_CHECK_EQUAL(destroyed[2], false);
free_items(mocks);
BOOST_CHECK_EQUAL(destroyed[0], true);
BOOST_CHECK_EQUAL(destroyed[1], true);
BOOST_CHECK_EQUAL(destroyed[2], true);
BOOST_CHECK(mocks[0] == nullptr);
BOOST_CHECK(mocks[1] == nullptr);
BOOST_CHECK(mocks[2] == nullptr);
}
The following are my questions:
Is the my so-called
FreeItemMock
a mock or a stub? I am not sure whether I pick the right name on my testee-class. According to the book The art of unit testing with examples in C#. A mock is used to test whether the interaction with other classed happened. I use myFreeItemMock
to test its destructor is called, but after invoke the free_item myFreeItemMock
actually does not exist anymore. It looks thedestroyed[3]
array variable is more like amock
.The function I want to test is doing job on a vector, so I need to prepare a array of data to test. Is it correct to hand write a serious of fixture like
data[0]
,data[1]
,data[2]
andassert
the result? Because the books also says a unit test should not have "logic" (likewhile
,for
-loop,if
) to increase its complexity.Or should I make a testing utility to help me produce the array data, and make another test for the utility?
Is it necessary to check the pre-test value of destroyed? Is it clearer to tell the reader that this function would make destroyed from 0 to 1? Or It is just too tedious?