views:

104

answers:

2

I have a bean that has a couple of beans injected with the autowire annotation (no qualifier). Now, for testing reasons I want to inject some mocks to the bean instead of the ones being autowired (some DAOs). Is there any way I can change which bean is being injected without modifying my bean? I don't like the idea of adding annotations my code just to test it and then remove then for production. I am using spring 2.5.

The bean look like this:

@Transactional  
@Service("validaBusinesService")  
public class ValidaBusinesServiceImpl implements ValidaBusinesService {

    @Autowired  
    OperationDAO operationDAO;  
    @Autowired  
    BinDAO binDAO;  
    @Autowired  
    CardDAO cardDAO;  
    @Autowired  
    UserDAO userDAO;  

    ...
    ...
}
+1  A: 

Use ReflectionTestUtils to set a different implementation manually in your unit tests.

This is actually one of the powers of dependency injection - it doesn't matter to the class how its dependencies are injected.

Bozho
I didn't know that class. It looks great!
santiagozky
A: 

IMHO you should provide setters to get the dependencies injected manually, too. Then it's a no-brainer in the unit test case. Maybe lower the visibility of the class to default if you don't want the setters to be invokable from outside of the package.

If you want to use mocks in integration test scenario you can create mock beans like this:

<bean class="….Mockito" factory-method="mock">
  <constructor-arg value="….OperationDao" />
</bean>

This would setup a Mockito mock for OperationDao as Spring bean.

Oliver Gierke
I agree that having setters and getters is a good idea, specially if at some point I use those classes without spring. But for this specific case I must not change the classes
santiagozky