Reputation: 7728
I'm writing unit tests for my webapp. Many of my test cases share the same boilerplate. For example, the tests for removing an item from the cart and updating the quantity of an item in the cart both start with navigating to the products page, searching for a product, and adding it to the cart.
Should such duplicated code be factored out of the unit tests somehow? Should I write a function add_item_to_cart
? But, I have another test test_add_to_cart
, which basically only consists of this duplicated boilerplate of adding to the cart.
Are unit tests by nature not DRY because of the need for each test to be independent?
Upvotes: 6
Views: 917
Reputation: 23062
Unit tests are supposed to test just one thing. A test that starts with "navigating to the products page, searching for a product, and adding it to the cart" -- that's three different things right there -- doesn't sound like a unit test at all, but an integration test. I suspect you thus actually have two different tests to build here.
Your integration test, in Cucumber or something similar, should consist of a series of steps:
When I navigate to the products page
And I search for a product
And I add it to the cart
You can define each step once and use it multiple times, making it nice and DRY.
Your unit test, on the other hand, should stub out all the setup necessary and just test the one thing you are interested in:
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 involve a lot of stubbing, it's an indicator that your code is not modular; the solution is to TDD and write the tests first, instead of adding them afterwards.
Upvotes: 3
Reputation: 14331
Refactor the common code at least into a function and meerly call this function at start up. You want to test the code particular to your test, not the repeated setup code (which should be tested elsewhere)
Upvotes: 2
Reputation: 35235
You should apply same principles to tests as to any other code.
Consider example then you change something that will break your tests. Do you wish to update test code in one place or in each of your tests?
I think answer is obvious.
Upvotes: 1