How much should DRY be my unit testing?

I am writing unit tests for my webapp. Many of my tests have the same template. For example, tests to remove an item from the basket and update the quantity of the product in the basket begin by going to the product page, searching for the product and adding it to the basket.

Should such duplicate code be exposed from unit tests in some way? Should I write an add_item_to_cart function? But I have another test_add_to_cart test, which basically consists only of this duplicated cart add template.

Are unit tests inherently not dry due to the need for an independent test?

+6
source share
3 answers

Unit tests should only test one thing . The test, which begins with "going to the product page, searching for the product and adding it to the basket," there are three different things, doesn’t look like a unit test at all, but an integration test. I suspect you have two different tests to create here.

Your integration test, in a cucumber or something similar, should consist of several stages:

 When I navigate to the products page And I search for a product And I add it to the cart 

You can identify each step once and use it several times, making it pleasant and dry.

Your unit test, on the other hand, should drown out all the necessary settings and just check one that interests you:

 before stub(cart) stub(product) click on "X" for item in cart it should... expect(cart not to contain item) expect(product count to be updated) 

If this turns out to be really complicated and involves a lot of stubbing, this is an indication that your code is not modular; the solution relates to TDD and records tests first, rather than adding them later.

+3
source

Reorganize the generic code, at least into a function, and call this function at startup. You want to check the code specific to your test, and not the reconfiguration code (which should be tested elsewhere).

+2
source

You must apply the same principles to testing as to any other code.

Consider an example, after which you change something that breaks your tests. Do you want to update the test code in one place or in each of your tests?

I think the answer is obvious.

+1
source

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


All Articles