Why I don't mock in tests 🤔

Jan 21, 2022 3:01 pm

Happy Friday!

I am taking a break from reading building codes to send you an email about another pretty dull seeming topic--test mocking.

The building codes are because we are about to begin building a home soon and I'm going to be that guy.

When people write automated tests against their code or systems there is a really common issue, which is how to deal with all the stuff their code and systems depend on. An example might be that I have a bit of code that represents a user in my system, but it gets the information from the database.

Now, when we want to write a test, suddenly we have to deal with those parts that are entangled. My little user thing needs a database, so for me to test, I have to do something about that database because it's required.

For most developers and groups I've worked with, this looks like the introduction of mocking tools. These tools more or less allow developers to write code that intercepts the request to those entangled bits and give it a pretend behavior. This allows developers to get back to testing the thing they want without really dealing with the other things that are entangled.

I don't mock.

This means that if some bit of code requires a database, then my tests will deal with the database. Now, most people will say this is ridiculous because I shouldn't have integration points like that or it's slow or other things, but here's the bottom line to me.

If my design tightly couples things together, then that's how I'll test it.

Going back to that user example, if I know I have to suffer writing a test that deals with a database I'm going to re-examine the design choices in the code. Does my User code really need a database? Probably not. So, I can refactor away the database and my tests also get simpler.

I want to come back to that last bit though because there is magic there.

By not mocking, I learn to design code that allows me to swap databases, frameworks, and services.

That is something people only ever talk about, but by leveraging tests without mocks I am forced to reconsider my designs to decouple things everywhere so my tests are fast and easy.

Good luck out there.