使用 Groovy 腳本進行 Context 組態
若要透過使用 Groovy Bean Definition DSL 的 Groovy 腳本為您的測試載入 ApplicationContext
,您可以使用 @ContextConfiguration
註解您的測試類別,並使用包含 Groovy 腳本資源位置的陣列來組態 locations
或 value
屬性。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
註解中省略 locations
和 value
屬性,則 TestContext Framework 會嘗試偵測預設的 Groovy 腳本。具體而言,GenericGroovyXmlContextLoader
和 GenericGroovyXmlWebContextLoader
會根據測試類別的名稱偵測預設位置。如果您的類別名為 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 腳本
您可以透過使用 以下清單示範如何在整合測試中組合兩者
|