4

I have the following classes:

public interface Emailer {}

@Named    
public class RealEmailer implements Emailer {}

@Named
public class NoOpEmailer implements Emailer {}

And my service class uses the real emailer:

public class SomeService {
    @Inject
    private Emailer emailer;
}

The question is, in my service test class (SomeServiceTest), how do I inject the Emailer in the service to use NoOpEmailer ? I'm using Spring for the DI framework.

2
  • What dependency injection framework do you want to use? Doing it with GUICE is different than Spring, is different than... Commented Jan 31, 2012 at 16:57
  • Sorry, I'm using Spring. I should've put it in the question. It's tagged with spring though. Commented Jan 31, 2012 at 17:00

2 Answers 2

4

If you can use Spring 3.1 you can use Profiles. This would allow you to provide two different implementations of the same bean (Emailer and NoOpEmailer). Then in your test you can use the @Profile("test") annotation to activate the test profile and your no op bean will be injected.

Sign up to request clarification or add additional context in comments.

Comments

1

Have you considered the possibility of making the field package scope rather then private as this would make it a lot simpler to set this field during your unit test (assuming your test class is in the same package as your subject).

If not, it seems to do this with Spring you would use ReflectionTestUtils#setField(Object target, String name, Object value) to inject this value into your class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.