Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject different implementation for testing

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.

like image 306
ryanprayogo Avatar asked Nov 02 '25 02:11

ryanprayogo


2 Answers

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.

like image 115
Alex Barnes Avatar answered Nov 03 '25 15:11

Alex Barnes


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

like image 24
Kingamajick Avatar answered Nov 03 '25 16:11

Kingamajick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!