What is the best way to inject mocked Spring @Autowired dependencies from a unit test?

Viewed 7594
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:

  1. Use Spring's ReflectionTestUtils in the test to inject the dependencies
  2. Add a constructor to MyService
  3. Add setter methods to MyService
  4. 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.

3 Answers
Related