TDD duplication of test data

I'm new to test-based development, and for the first time I'm trying to use it in a simple project.

I have a class and I need to test the creation, insertion and deletion of objects of this class. If I write three separate test functions, I need to duplicate the initialization codes in another function. On the hand, if I put all the tests in one test function, this contradicts one test for each function. What should I do?

Here's 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); } 
+4
source share
2 answers

Change the duplication in your tests.

Depending on your test environment, there may be support for determining the installation method that is called before each test run, and the break method that is called after each test.

Regardless, you can extract common material to repeat the call of only one common setting.

If you tell us which language and test structure you use, we can give more specific recommendations.

+4
source

Instead of β€œOne test for each function,” think of it as β€œOne aspect of behavior for each function.”

What adds you an object? How about deleting an object? Why are they valuable? How can you say that you made them? Write an example of code usage and why this behavior is valuable. This will be your test.

When you figure out what kind of behavior you are interested in, extract duplication only if it makes the test more readable. TDD is not only testing; it is also about providing documentation and will help you think about the responsibility of each element of the code and the design of that code. Tests are likely to be read much more than they are written, so readability should be the first.

If necessary, put all the behavior in which you are interested in one way and just make sure that it is readable. If necessary, you can add comments.

+6
source

Source: https://habr.com/ru/post/1337780/


All Articles