[英]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). 我有一个bean,其中有几个注入了自动装配注释的bean(没有限定符)。 Now, for testing reasons I want to inject some mocks to the bean instead of the ones being autowired (some DAOs). 现在,出于测试原因,我想向bean注入一些模拟,而不是自动装配的模拟(某些DAO)。 Is there any way I can change which bean is being injected without modifying my bean? 有什么方法可以在不修改我的bean的情况下更改注入的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. 我正在使用Spring 2.5。
The bean look like this: Bean看起来像这样:
@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. 使用ReflectionTestUtils
在单元测试中手动设置其他实现。
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. 这会将OperationDao
的Mockito
模拟设置为Spring bean。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.