XML リソースを使用したコンテキスト設定
XML 構成ファイルを使用して ApplicationContext をテスト用にロードするには、テストクラスに @ContextConfiguration のアノテーションを付け、XML 構成メタデータのリソースの場所を含む配列で locations 属性を構成します。プレーンパスまたは相対パス(たとえば、context.xml)は、テストクラスが定義されているパッケージに相対的なクラスパスリソースとして扱われます。スラッシュで始まるパスは、絶対クラスパスの場所として扱われます(たとえば、/org/example/config.xml)。リソース URL を表すパス(つまり、接頭辞 classpath:、file:、http: など)がそのまま使用されます。
Java
Kotlin
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "/app-config.xml" and
// "/test-config.xml" in the root of the classpath
@ContextConfiguration(locations = {"/app-config.xml", "/test-config.xml"}) (1)
class MyTest {
// class body...
}| 1 | ロケーション属性を XML ファイルのリストに設定します。 |
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from "/app-config.xml" and
// "/test-config.xml" in the root of the classpath
@ContextConfiguration(locations = ["/app-config.xml", "/test-config.xml"]) (1)
class MyTest {
// class body...
}| 1 | ロケーション属性を XML ファイルのリストに設定します。 |
@ContextConfiguration は、標準 Java value 属性を介して locations 属性のエイリアスをサポートします。@ContextConfiguration で追加の属性を宣言する必要がない場合は、次の例に示す短縮形を使用して、locations 属性名の宣言を省略し、リソースの場所を宣言できます。
Java
Kotlin
@ExtendWith(SpringExtension.class)
@ContextConfiguration({"/app-config.xml", "/test-config.xml"}) (1)
class MyTest {
// class body...
}| 1 | locations 属性を使用せずに XML ファイルを指定します。 |
@ExtendWith(SpringExtension::class)
@ContextConfiguration("/app-config.xml", "/test-config.xml") (1)
class MyTest {
// class body...
}| 1 | locations 属性を使用せずに XML ファイルを指定します。 |
@ContextConfiguration アノテーションから locations 属性と value 属性の両方を省略した場合、TestContext フレームワークはデフォルトの XML リソースの場所を検出しようとします。具体的には、GenericXmlContextLoader と GenericXmlWebContextLoader は、テストクラスの名前に基づいてデフォルトの場所を検出します。クラスの名前が com.example.MyTest の場合、GenericXmlContextLoader は "classpath:com/example/MyTest-context.xml" からアプリケーションコンテキストをロードします。次の例は、その方法を示しています。
Java
Kotlin
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration (1)
class MyTest {
// class body...
}| 1 | デフォルトの場所から構成をロードしています。 |
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration (1)
class MyTest {
// class body...
}| 1 | デフォルトの場所から構成をロードしています。 |