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:
- Use Spring’s ReflectionTestUtils in the test to inject the dependencies
- Add a constructor to MyService
- Add setter methods to MyService
- Relax the dependency visibility to package-protected and set the fields directly
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.
Use
ReflectionTestUtilsor 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.