import org.springframework.beans.factory.annotation.Autowired;
class MyService {
@Autowired private DependencyOne dependencyOne;
@Autowired private DependencyTwo dependencyTwo;
public void doSomething(){
//Does something with dependencies
}
}
When testing this class, I basically have four ways to inject mock dependencies:
Which is the best and why?
--- UPDATE ---
I guess I should have been a bit clearer - I am only talking about "unit" style tests, not Spring "integration" style tests where dependencies can be wired in using a Spring context.
Setter Injection is the preferred choice when a number of dependencies to be injected is a lot more than normal, if some of those arguments are optional than using a Builder design pattern is also a good option. In Summary, both Setter Injection and Constructor Injection have their own advantages and disadvantages.
@Autowired annotation is used to let Spring know that autowiring is required. This can be applied to field, constructor and methods. This annotation allows us to implement constructor-based, field-based or method-based dependency injection in our components.
Use ReflectionTestUtils
or put a setter. Either is fine. Adding constructors can have side effects (disallow subclassing by CGLIB for example), and relaxing the visibility just for the sake of testing is not a good approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With