Alex Rivera | Logout

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

Asked 2011-07-27T07:36:33.720
17
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.

Edit
Report

1 Answer

20

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.

answered 2011-07-27T07:42:36.187

Your Answer