Skip to main content
3 of 5
deleted 11 characters in body
Jamal
  • 34.9k
  • 13
  • 133
  • 237

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

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:

  1. 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 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 variable is more like a mock.

  2. 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 unit test should not have "logic" (like while, 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?

  1. 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?
Chen OT
  • 247
  • 3
  • 7