Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TDD duplication of test data

I'm new to test driven development and first time I'm tring to use it in a simple project.

I have a class, and I need to test creation, insertion and deletion of objects of this class. If I write three seperate test functions I need to duplicate initialization codes in other function. On the hand if I put all tests in one test function then it is a contradiction with one test per function. What should I do?

Here the situation:

tst_create()
{
   createHead(head);
   createBody(body);
   createFoot(foot);
}

tst_insert()
{
   createHead(head);
   createBody(body);
   createFoot(foot);

   obj_id=insert(obj); //Also I need to delete obj_id somehow in order to preserve old state
}

tst_delete()
{
   createHead(head);
   createBody(body);
   createFoot(foot);

   obj_id=insert(obj); 

   delete(obj_id);
}

vs

tstCreateInsertDelete()
{
   createHead(head);
   createBody(body);
   createFoot(foot);

   obj_id=insert(obj);

   delete(obj_id);
}
like image 506
Rob Ashton Avatar asked Dec 28 '22 02:12

Rob Ashton


1 Answers

Rather than "One test per function", try thinking about it as, "One aspect of behaviour per function".

What does inserting an object give you? How about deleting an object? Why are these valuable? How can you tell you've done them? Write an example of how the code might be used, and why that behaviour is valuable. That then becomes your test.

When you've worked out what the behaviour is that you're interested in, extract out the duplication only if it makes the test more readable. TDD isn't just about testing; it's also about providing documentation, and helping you think about the responsibility of each element of code and the design of that code. The tests will probably be read far more than they're written, so readability has to come first.

If necessary, put all the behaviour you're interested in in one method, and just make sure it's readable. You can add comments if required.

like image 194
Lunivore Avatar answered Jan 12 '23 20:01

Lunivore