What Is Unit Testing?

This is a critical building block when it comes to testing your Spring Boot apps (and really any apps), so let's knock this out quick.

1. What is a unit?

The smallest public piece of logic in your project. Usually this is a method in a class, but could also be larger pieces like an entire class if the API should be hidden.

I say public because making code public means you expect outside actors to leverage it. Private or protected methods are not meant to have outside actors, so you should test the methods and classes that leverage that non-public code.

2. Ok, a unit, that's easy. What is defined as unit testing then?

Unit testing is exercising the code JUST IN THAT UNIT. If the code you want to test interacts with other code in your system or dependencies outside of your system, unit testing ignores those outside influences.

3. Wait, how can I ignore everything else? I need that code to make this work...

Think about if you were cooking dinner and didn't have an ingredient in the recipe - do you just forget the whole thing and order pizza? Ok, maybe, but most of the time you just substitute something else. That's what you need to do here.

The concept is called mocking. You want to replace that outside code with a fake that looks like it, but does nothing. You'll intercept that call to the mock and provide whatever you want to respond with.

This makes testing edge cases and errors WAAAAY easier, and in some cases it is otherwise impossible. Mocking is a necessity in modern software development.

Whew, now that you got that out of the way, read about the other types of testing you should be doing in Spring Boot.

Thanks for reading and I hope this was helpful!

Comments powered by Talkyard.