[英]Spring bean autowire for testing
我有很多關於該自動接線的春季服務:
@Autowired
private SmartCardService smartCardService;
我需要一個虛擬類進行測試,並且定義了擴展原始類的此類:
@Service
public class DummySmartCardService extends SmartCardService{
...
}
我如何確定所有自動裝配都將使用虛擬對象而不是原始服務,而不更改所有自動裝配注釋?
謝謝。
考慮使用@Primary批注。 看這里
DummySmartCardService
從應用程序上下文文件的測試版本加載DummySmartCardService
bean,這樣就無需更改測試代碼。
@ContextConfiguration(locations = {"classpath:test-services.xml"})
使用@Resource批注或@Qualifier和@Qualifier來區分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;
}
恕我直言,您應該看一下Springockio,以正確,輕松地模擬 Spring bean。
您可以通過以下方式將bean替換為模擬對象或將其包裝為Spy:
@ContextConfiguration(loader = SpringockitoContextLoader.class,
locations = "classpath:/context.xml")
public class SpringockitoAnnotationsMocksIntegrationTest extends
AbstractJUnit4SpringContextTests {
@ReplaceWithMock
@Autowired
private InnerBean innerBean;
@WrapWithSpy
@Autowired
private AnotherInnerBean anotherInnerBean;
....
}
這不僅是一種干凈的方法(您不需要通過添加限定符或配置文件來更改正在測試的代碼),而且還允許您使用Mockito的功能來進行模擬 ,驗證和監視,這非常好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.