Reputation: 767
I tend to write a lot of applications that, say, will expose API to a logic, which will call other APIs within the same logic, and then persist some form of data to a database at the end. So, in other words, I tend to have a method call that encapsulates calling other APIs, processing data and then persisting to the database.
I'm familiar with TDD (test driven development), but I find it difficult to practice, because the last thing I want is persisting useless data in production database while running mandatory tests, and also calling external APIs that I don't control and messing up their database in turn.
I'm probably looking at it the wrong way.
How do I practice efficient TDD and evade this problem?
Upvotes: 1
Views: 125
Reputation: 57279
How do I practice efficient TDD and evade this problem?
Design.
Roughly, we arrange our code so that it is a composition of modules of two flavors
So the code that actually needs to talk to the database should be of the second type; no branching, trivial operations, and most importantly it doesn't need to change very often.
The code that we write that feels inherently risky? that goes into an "easy to test" module. These modules are only loosely coupled to their simpler cousins - it should be easy to substitute a "test" implementation for the "real" one. Thus, instead of talking to "the database" during our testing, we talk to some in memory collection that just gives us scripted responses.
In short, we arrange our code so that it is easy to test where the mistakes are.
As for the hard to test bits; well, perhaps we measure the risks in other ways, or we run those tests at a different cadence, or we defer the testing of them to functional tests, or....
Upvotes: 1