我有很多关于这个autowire:的spring服务
@Autowired
private SmartCardService smartCardService;
我需要一个用于测试的伪类,我定义了这个扩展原来的类:
@Service
public class DummySmartCardService extends SmartCardService{
...
}
在不更改所有Autowired注释的情况下,我如何确保所有autowire都将采用伪服务而不是原始服务?
谢谢。
考虑使用@Primary注释。请参阅此处
从应用程序上下文文件的测试版本加载DummySmartCardService
bean,这样就不需要对测试中的代码进行任何更改
@ContextConfiguration(locations = {"classpath:test-services.xml"})
使用@Resource注释或@Qualifier,With@Qualifieer来区分bean类型:
@Autowired
@Qualifier("testing")
private SmartCardService smartCardService;
@Service
@Qualifier("testing")
public class DummySmartCardService extends SmartCardService{
...
}
或者使用按名称语义的@Resource:
@Resource("dummySmartCardService")
private SmartCardService smartCardService;
@Service("dummySmartCardService")
public class DummySmartCardService extends SmartCardService{
...
}
理论上你可以使用@Qualifier("beanName")
,但这是不鼓励的。
但它认为,如果您有一个Spring配置文件,只在测试中加载与测试相关的存根,那会更好:
@Service
@Profile("test")
public class DummySmartCardService extends SmartCardService{
...
}
@ContextConfiguration(locations = {"classpath:services.xml"})
@ActiveProfiles("test")
public class TestSuite{
@Autowired
private SmartCardService smartCardService;
}
IMHO您应该看看Springockio,了解对Spring bean的适当且相当容易的嘲讽。
你可以用模拟来代替你的bean,或者用间谍来代替它:
@ContextConfiguration(loader = SpringockitoContextLoader.class,
locations = "classpath:/context.xml")
public class SpringockitoAnnotationsMocksIntegrationTest extends
AbstractJUnit4SpringContextTests {
@ReplaceWithMock
@Autowired
private InnerBean innerBean;
@WrapWithSpy
@Autowired
private AnotherInnerBean anotherInnerBean;
....
}
这不仅是一种干净的方式(您不需要通过添加限定符或配置文件来更改正在测试的代码),而且还允许您使用Mockito的功能进行嘲讽、验证和间谍活动,这非常棒。