简体   繁体   中英

inject a mockups to a bean that has @Autowired annotations

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;  

    ...
    ...
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM