How can we use test-driven development for JSON parsing? Most developers are concerned with ways to implement the production code. There are various approaches, various libraries… But what about the unit test side of things?
If we write effective unit tests, the design can appear incrementally. And with a strong suite of tests, you're free to change the implementation—even radically. When the results are guaranteed by tests, whatever approach you take, or library you use, becomes an implementation detail!
Last time, we looked at design principles, such as sticking to the Single Responsibility Principle and returning a Response Model. This time, let's look at:
- Test principles
- A TDD demo in Objective-C
Test Principles, Applied to JSON Parsing
From an execution perspective: A good unit test reacts to things that matter, and ignores things that don't matter. (This is the secret to avoiding fragile tests.)
A good unit test highlights things that matter, and hides things that don't matter.
But now let’s apply this to readability: A good unit test highlights things that matter, and hides things that don’t matter.
Ideally then, test input should be plainly visible in the first section of a unit test. If it’s repeated, extract it but keep it close to the tests.
Yet so many developers put their test JSON (or XML) into external files. I think the reason folks do this is it’s easy to think about. You can just copy and paste an entire response.
When a complex response is reused across test suites, this makes sense. But that feels more like integration testing. A unit test is better when it’s tightly focused.
So for parsing, I try to keep relevant input inside the test.
Screencast: A TDD Demo in Objective-C
Let’s apply the design principles and test principles, and do some test-driven development! I’m using Objective-C in this 11-minute screencast.
The screencast illustrates the red-green-refactor TDD steps. If you haven’t done it yourself, it may look odd. In particular, “doing the easiest thing that passes” can look silly. But it serves an important purpose:
By making a change in the production code, we get a test to pass. This is like flipping a switch and seeing the light change. It demonstrates that the two sides are connected.
Using JSON parsing as a backdrop, we’ve looked at
- design principles,
- test principles, and
- the red-green-refactor flow of TDD.
Finally, note that the design is not preplanned. TDD supports emergent design.
So what’s next? We’ll see what’s different about parsing JSON in Swift.
Does your project have unit tests that use external files as inputs? Can you move any of it inside of tests? Then can you trim the input?
[This post is part of the series TDD Sample App: The Complete Collection …So Far]