Unit Testing - You're Doing It Wrong

Discover a new approach to unit testing that focuses on testing the service as a whole, rather than individual methods or layers.

What do you think of when you hear the phrase “Unit Testing”? Do you think of testing each method of your service individually and independently, while mocking everything else? Testing your endpoint layer, testing your business logic layer, testing your repository layer? If so, then your thinking about unit testing wrong.

Yes, this is what we were taught in school. Write a method and then write a test for this method, or if you’re fancy and follow TDD - you write your failing test, then write your method and watch your test pass.

There’s a better way

This granularity of testing is time consuming and inefficient. When we talk about unit testing, the “unit” under test should be the service itself. Your time is better spent testing the interface to your service: “given this input, I expect this output”.

unit testing

Using this mindset around unit testing, the number of tests can go from hundreds down to tens, all while maintaining the same amount of test coverage. But wait - why do we care how many tests there are? Code, whether it’s production or test code, takes time to write and takes and time to maintain. Our goal as software engineers should be to confidently test our code while minimizing the burden the tests themselves create.

Solitary vs sociable unit testing

The traditional testing strategy mentioned is called solitary unit testing. This is where things are tested individually and independently. The better way is called sociable testing. Here we don’t mock out dependencies and test the actual flow of code.

Further Reading