

I couldn’t, because I had no way to set the mock component instance to the private field. All I wanted was to inject a mock component to the bean under tests. The answer was " because I have no way to set a value to the private field". I was going to use DeltaSpike as usual, but something made me stop and ask myself " Why do I need to start a DI container to run some basic unit tests?". I needed to start a CDI container within my tests.

I was writing a CDI based project and I had to write a few unit tests on classes that were using private field dependency injection. When I figured out private field dependency injection was evil Now, lets face the reality: how bad is it? Wait! I'm not just going to pull up a CONS list and it. We already know how good is to use private field dependency injection. Once the DI container sets a value there, nothing else can change it, of course, unless we put on some gloves and use reflection to dig (this is actually how the DI container changes the field's value). If the Order class does not offer a setter method to modify the payments field nor a constructor, then, we can assume the Order class is Immutable. Pay attention on the payments field: Encapsulation with zero effortīeing private, the payments field is well encapsulated, meaning no external component will have access to it, unless we expose it willingly through a getter method. They also manage beans lifecycle and do other stuff I'm not going to be talking about. I will focus on how we use the DI containers and not on what they offer. In Java, DI containers do more than beans lookup. The dependency injection containers allow you to select the desired component implementation to be injected into a specific component, or they might just find one implementation for you in your classpath, or better, they can create one implementation on the fly, as Spring does (Spring-Data). Dependency injection is a great way of decoupling system components, assuming they are written using a contract-implementation approach.
