[英]reduce spring ContextConfiguration boilerplate in tests
我想知道是否有辦法減少我們目前為集成測試編寫的樣板數量。
罪魁禍首是ContextConfiguration,我們目前向其中發送7個不同的字符串。
我們的測試之一如下所示(刪除了有效負載代碼):
@ContextConfiguration(locations = {"classpath:properties-config.xml",
"classpath:dataSources-config.xml",
"classpath:dao-config.xml",
"classpath:services-config.xml",
"classpath:ehcache-config.xml",
"classpath:test-config.xml",
"classpath:quartz-services.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@Category(IntegrationTest.class)
public class TerminalBuntsPDFTest {
@Autowired
private JobService jobService;
@Test
public void testCode() throws SystemException {
assertTrue("Success", true);
}
}
而要加載的xml文件的規范占用了大量空間。 我們正處於從xml遷移到注釋的過程中(非常緩慢),但是在該項目中還有很多工作要做。
我們正在使用Spring 3.2。
那這種模式呢:
@ContextConfiguration(locations = {"classpath:properties-config.xml",
"classpath:dataSources-config.xml",
"classpath:dao-config.xml",
"classpath:services-config.xml",
"classpath:ehcache-config.xml",
"classpath:test-config.xml",
"classpath:quartz-services.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@Category(IntegrationTest.class)
public abstract class BaseTest {
}
// ....
public class TerminalBuntsPDFTest extends BaseTest {
@Autowired
private JobService jobService;
@Test
public void testCode() throws SystemException {
assertTrue("Success", true);
}
}
// ....
public class TerminalBuntsPDFTest2 extends BaseTest {}
這將使您只能在父抽象類中放置一次配置。
基於注釋的方法是創建一個Spring Configuration Java類,如下所示:
@Configuration("testConfig")
@ImportResource({
"dataSources-config.xml",
"dao-config.xml",
"services-config.xml"
})
public class TestConfiguration {
// TO create a spring managed bean
@Bean
MyBean myBean() {
return new MyBean();
}
}
然后,可以像這樣注釋測試類以加載配置:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes=TestConfiguration.class,
loader=AnnotationConfigContextLoader.class
)
@Category(IntegrationTest.class)
public class TerminalBuntsPDFTest {
這只是一個簡單的示例,可能不會編譯,但可以使您走上正軌
一些相關文檔:
http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.