Skip to main content

Posts

Showing posts from May 7, 2022

Do not use magic in unit tests

Greetings! Working in legacy system is both fun and hard. It becomes harder due to lack of tests. Not only that, it is difficult to write tests due to the ways code is written. As our legacy system doesn't have a DI framework like Spring, we are maintaining object lifecycle manually. We have a policy to create singletons (I do not know why, I plan to remove them anyway) which made them harder for unit tests. The way to write unit tests for these classes is using reflection and mocking frameworks (scary isn't). Let's see a basic example of such a class. public final class AppointmentRepository { private AppointmentRepository() { } private static class LazyHolder { private static final AppointmentRepository INSTANCE = new AppointmentRepository(); } public static AppointmentRepository getInstance() { return LazyHolder.INSTANCE; } } public final class AppointmentService { private final AppointmentRepository appointmentRepository; private AppointmentS