Maintainable and readable test code is crucial to establish a good test coverage which in turn enables implementing new features and performing refactorings without the fear of breaking something. This post contains many best practices that I collected over the years of writing unit tests and integration tests in Java. It involves modern technologies like JUnit5, AssertJ, Testcontainers, and Kotlin. Some recommendations might be obvious to you, but some might conflict with what you’ve read in books about software development and testing.
Testing classes in isolation and with mocks is popular. But those tests have drawbacks like painful refactorings and the untested integration of the real objects. Fortunately, it’s easy to write integration tests that hit all layers. This way, we are finally testing the behavior instead of the implementation. This post covers concrete code snippets, performance tips and technologies like Spring, JUnit5, Testcontainers, MockWebServer, and AssertJ for easily writing integration tests. Let’s discover integration tests as the sweet spot of testing.