Java: Is it okay to abuse Spring beans (@Component) rather than use static final utility classes

dependency-injectionjavaspringstatic

I'm torn between using DI and static utility classes on my code.

I currently created a DateUtil static class that is only meant to be accessed statically. This class is responsible for just creating and manipulating dates using a variety of libraries with absolutely no external 3rd party dependency.

Everything looks fine but now unit testing becomes messier since now we have to use PowerMockito to properly stub the behavior of the static class.

On the contrary, if I removed the static-ness of DateUtil and converted it into a Spring @Component, then now unit tests can be a tad bit easier, however, now we have all these dependencies everywhere and I'm not sure that this is the purpose of Spring managed beans.

How should I proceed with this? Is it okay to using Spring beans everywhere and just forget about static code entirely? Is it okay to abuse Spring's DI capabilities? When is it "too much DI"?

Best Answer

The prevailing assumption that static methods are not unit-testable seems to have arisen from developers being accustomed to writing unit tests against instantiable class instances, and all of the things that come with that like mocks, stubs, interfaces, dependency injection, etc. You can't do any of that with static classes. However ...

Static methods operating on (more or less) primitive types like Date don't require any of that. Assuming that your static methods are pure (i.e. contain no side-effects and avoid static state), you can test them by merely calling them with a test value and asserting the correct return result.

That's it. Doing anything else is going to drown your fellow programmers in an unnecessary sea of complexity for no additional benefit.

Non-static classes have a very specific purpose. If you need that purpose, by all means use one. But if you don't need it, why use it if your only rationale is that you can't apply your usual class-testing techniques? The remedy to that is to learn a more suitable testing technique, not shoehorn your method under test into a class just because you think you need a container to test it in.

Further Reading
Is static universally “evil” for unit testing and if so why does Resharper recommend it?