views:

259

answers:

1

Hi

a little background:

I am Using Spring 2.5, and specifically spring IOC and annotations.

I am using @Autowired in my code (the Autowiring is done by type) and use @Component for exposing Classes to the Automatic wiring.

The situation described bellow arose while i tried to test my code.

now to the problem:

Note: i use a different Spring Context for the Test environment.

I have a class FOO which is @Autowired but in the test context i want to use a different class of the same type MockFoo (extends FOO)

The Spring Setup of course fails do so automatically due to multiple options for the Dependency Injection of the FOO class (both FOO and MockFOO comply to the Type check)

I am looking for a way to inject the test bean instead of the original bean.

I expected Spring to allow using the Context configurion file to override a bean injection or to order Spring not to autowire a specific bean

BUT

All these option seem to exists only for the beans which were originally defined in the Spring Context Configuration file

+1  A: 

Use ReflectionTestUtils to manually set the Mock in place of the autowired dependency (for that purpose your mock must not be spring managed, so that no ambiguity exists)

Bozho
this is a good solution when you do not have the same instance injected to multiple classes - but in a big project where a class acts as a service provider(it is a singleton) and is injected to many classes, i hope there is some easier/better solution to avoid injecting each class that uses the original
Mark