Instance copy module and assignment operator

I am writing unit tests for multiple classes (C ++) and faced a problem trying to write a unit test for copy constructor and assignment operator. The main thing that can be wrong is that the programmer adds a member to the class and then forgets to update the c'ctor and / or operator =.

I could, of course, write a unit test line by line:

class MyClass()
{
public:

    int a, b;
    non_trivial_copyable nasty;

    MyClass& operator=(const MyClass& _r)
    {
        if(this == &r)
          return *this;
        a = _r.a;
        b = _r.b;
        nasty = acquire_non_trivial_copyable();
    }
};


TEST(My_Class_copy_op)
{
  MyClass m1;
  m1.a = m1.b = 2;

  MyClass m2 = m1;
  VERIFY(m2.a == 2);
  VERIFY(m2.b == 2);
}

      

Very well. now the programmer adds the c member but does not update the statement and test case.

class MyClass()
{
public:
    float c;
// ...
}

      

The test test will still succeed even if the operator is now broken.

Now we can do the following:

TEST(My_Class_copy_op)
{
// Aha! Fails when programmer forgets to update test case to include checking c
   static_assert(sizeof(MyClass) == 8);
// Meh, also fails on an architecture where the size of MyClass happens to be != 8

   // ...
}

      

I couldn't find any good information on how to solve this, but I'm sure someone must have encountered this before !? Is it so obvious that I missed it entirely ??

+3


source to share


1 answer


Explicit testing of the copy constructor is fine, but it probably happens around the hive. More often than not, this is not the case, the copy constructor itself is a detail that you don't need to explicitly test. Instead, you will most likely want to write a suite of tests that work on your copied object and make sure that the work produces the correct results. Like this:



MyClass a;
// Now initialize a with stuff it needs to do its job

// Copy a into b
MyClass b = a;

// Make b do its job and make sure it succeeds
VERIFY(b.DoWork());

      

+7


source







All Articles