DEV Community

Luciano Graziani
Luciano Graziani

Posted on

The value of unit or integration testing

Where are the tests?

Comic by CommitStrip: http://www.commitstrip.com/en/2017/02/08/where-are-the-tests/

TL;DR: Try to write unit/integration tests, at least, for you core processes. Your future self will thank you.


A few days ago I had to refactor two processes in a stock system: sales and purchases. Both have, at least, one step in common: they query a list of products filtering by a list of IDs. Both use the same data except that sales uses the sale_price (aliased as unit_price) and purchases uses the unit_price. Both manage a "unit price", one as the unit price for sale, and another for purhcase.

The sales process was written by me and the purchases process was written by a teammate, so, even when they have that step in common, both processes did in different ways. It's OK and normal. We didn't knew what they'll have in common until we wrote the code.

Those processes are extremely important and sensitive because they are the core of the system AND manage money. Because of that, we decided to add unit and integration tests for each constraint they have.

Because of that decision, even when my teammate, who isn't used to write tests, didn't wanted to "waste" time written them, today I could refactor both processes and prevented a dangerous bug to emerge:

While refactoring that common step in one method, I decided to query every attribute required by the sales and purchases processes, which means that now both will have accessible the sale_price and unit_price props. But I didn't remembered that inside the sales process, the total attribute was being calculated using the old sale_price alias: unit_price. With the change, everything still worked fine, but the total, instead of multipliying the sale_price for the amount of products, was using the real unit_price.

Only because the snapshot tests warned me about a diff, I could catch the error. Only because we decided to add tests to our processes, instead of letting the user catch us for us, with everything that means.

I hope this experience will motivate you to write tests!

Thank you for reading!

Top comments (0)