Tuesday, June 15, 2021

ABC TDD API


Last night I attended How to TDD a REST API, a webinar by Gil Zilberfeld. In it, Gil described an experiment he's running to try to use test-driven development for a service built with Spring Boot in Java. As part of this, he is building unit and API tests at the same time.

The code is available in GitHub and you can follow the kindergarten moves he talked us through by reading the src and main directories in parallel in numerical order.

What insights did he get from his experience? Well, as you might expect, with all the additional weight of a framework and internal and external dependencies, there is a lot of friction. 

But he still thinks there is still value in using TDD, or perhaps its spirit. His recommendations include:

  • small steps
  • a hexagonal architecture for aggressive abstraction
  • very thin adapters (code that interfaces your code to the external world)
  • code and data that is framework agnostic as far as possible
  • small steps
  • refactoring eagerly for readability
  • refactoring on red sometimes
  • committing (and reverting) frequently and at a fine granularity
  • small steps

If you're wondering why small steps is on the list so many times it's because that point was hammered home. It is easy to go wrong so protect yourself with small steps. In fact, adjust your model of TDD as a cycle of red, green, refactor to be something more like red, shuffle, red, shuffle, refactor, shuffle, green, refactor.

I think it will be interesting to see the development of strategies for testing a given piece of functionality at the unit level and/or the API level. As a starting point Gil suggested that precise logic would be in the unit tests and more behavioural logic in the API tests, which makes sense to me.

Finally, one point not addressed in the talk was the overhead of running the tests themselves. Gil hasn't got far enough into the project that starting the service to run the tests is a major cost or a motivation not to run them.

No comments:

Post a Comment