Skip to main content
1 of 5
Chen OT
  • 247
  • 3
  • 7

My test code with vector and mock

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 ;
};

And 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 followings are my questions.

Q1. The my so-called FreeItemMock is 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 my FreeItemMock to test its destructor is called, but after invoke the free_item my FreeItemMock actually does not exist anymore. It looks the destroyed[3] array varaible is more like a mock.

Q2. 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] and assert the result? Because the books also says a unittest should not have "logic" (like while, for-loop, if) to increase its complexity.

Or I should make a testing utility to help me to produce the array data, and make another test for the utility?

Q3. Is it necessary to check the pre-test value of destroyed? Is it more clearer to tell reader that this function would make destroyed from 0 to 1. Or It is just too tedious.

Thanks.

Chen OT
  • 247
  • 3
  • 7