Tests Make Better APIs

Testing things in isolation may give a better view of your APIs.

After reading the integration tests chapter, you may end up with the impression that I don't like unit tests1.

Actually, I think they provide some good intrinsic values.

For example, as mentioned before, they can provide a better look at the adherence to the design.

But, at the same time, they give a better view of your internal -- and even external -- APIs.

For example, you're writing the tests for the view layer -- 'cause, you know, we write everything in layers; layers on top of layers2 -- and you're noticing that you have to keep a lot of data (state) around to be able to make the calls to the controller. Or that you have similar calls, but the parameters are sometimes switched (say, one function gets a token and a user ID, and another function gets a user ID and a token -- why?) That's a sign that you may have to take a better look at the controller API.

Not only that, but take, for example, the fact that you're working on a library -- which will be called by someone else -- and you're writing tests for the most external layer, the layer that will be exposed by that library. And, again, you're noticing that you have to keep a lot of context around, lots of variables, variables coming from different places and similar calls using parameters in different ways. Your tests will look like a mess, don't they? That's because the API is a mess.

Unit testing your layers makes you the user of that layer API, and then you can see how much one would suffer -- or, hopefully, enjoy -- using that.

1

Again, let's ignore for a second that there are no "unit" in "unit tests"...

2

And layers all the way down, like turtles.