使用 Groovy 腳本進行 Context 組態

若要透過使用 Groovy Bean Definition DSL 的 Groovy 腳本為您的測試載入 ApplicationContext,您可以使用 @ContextConfiguration 註解您的測試類別,並使用包含 Groovy 腳本資源位置的陣列來組態 locationsvalue 屬性。Groovy 腳本的資源查閱語意與 XML 組態檔 所述的語意相同。

啟用 Groovy 腳本支援
如果 Groovy 在類路徑上,則會自動啟用在 Spring TestContext Framework 中使用 Groovy 腳本載入 ApplicationContext 的支援。

以下範例示範如何指定 Groovy 組態檔

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "/AppConfig.groovy" and
// "/TestConfig.groovy" in the root of the classpath
@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"}) (1)
class MyTest {
	// class body...
}
1 指定 Groovy 組態檔的位置。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from "/AppConfig.groovy" and
// "/TestConfig.groovy" in the root of the classpath
@ContextConfiguration("/AppConfig.groovy", "/TestConfig.Groovy") (1)
class MyTest {
	// class body...
}
1 指定 Groovy 組態檔的位置。

如果您從 @ContextConfiguration 註解中省略 locationsvalue 屬性,則 TestContext Framework 會嘗試偵測預設的 Groovy 腳本。具體而言,GenericGroovyXmlContextLoaderGenericGroovyXmlWebContextLoader 會根據測試類別的名稱偵測預設位置。如果您的類別名為 com.example.MyTest,則 Groovy context loader 會從 "classpath:com/example/MyTestContext.groovy" 載入您的應用程式 Context。以下範例示範如何使用預設值

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 從預設位置載入組態。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 從預設位置載入組態。
同時宣告 XML 組態和 Groovy 腳本

您可以透過使用 @ContextConfigurationlocationsvalue 屬性,同時宣告 XML 組態檔和 Groovy 腳本。如果組態資源位置的路徑以 .xml 結尾,則會使用 XmlBeanDefinitionReader 載入。否則,會使用 GroovyBeanDefinitionReader 載入。

以下清單示範如何在整合測試中組合兩者

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "/app-config.xml" and "/TestConfig.groovy"
@ContextConfiguration({ "/app-config.xml", "/TestConfig.groovy" })
class MyTest {
	// class body...
}
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "/app-config.xml" and "/TestConfig.groovy"
@ContextConfiguration("/app-config.xml", "/TestConfig.groovy")
class MyTest {
	// class body...
}