Spring 5のSpringJUnitConfigおよびSpringJUnitWebConfigアノテーション
1. 前書き
この簡単な記事では、Spring 5で利用可能な新しい@SpringJUnitConfigおよび@SpringJUnitWebConfigアノテーションを見ていきます。
テストの作成をより簡単かつ迅速にするThese annotations are a composition of JUnit 5 and Spring 5 annotations。
2. @SpringJUnitConfig
@SpringJUnitConfigは、次の2つの注釈を組み合わせたものです。
-
SpringExtensionクラスでテストを実行するための@ExtendWith(SpringExtension.class) from JUnit 5および
-
Springコンテキストをロードするための@ContextConfiguration from Spring Testing
テストを作成して、このアノテーションを実際に使用してみましょう。
@SpringJUnitConfig(SpringJUnitConfigIntegrationTest.Config.class)
public class SpringJUnitConfigIntegrationTest {
@Configuration
static class Config {}
}
Notice that, in contrast to the @ContextConfiguration, configuration classes are declared using the value attribute.ただし、リソースの場所はlocations属性で指定する必要があります。
これで、Springコンテキストが実際にロードされたことを確認できます。
@Autowired
private ApplicationContext applicationContext;
@Test
void givenAppContext_WhenInjected_ThenItShouldNotBeNull() {
assertNotNull(applicationContext);
}
最後に、ここに@SpringJUnitConfig(SpringJUnitConfigTest.Config.class):の同等のコードがあります
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SpringJUnitConfigTest.Config.class)
3. @SpringJUnitWebConfig
@SpringJUnitWebConfigcombines the same annotations of @SpringJUnitConfig plus the @WebAppConfiguration from Spring testing –WebApplicationContextをロードします。
このアノテーションがどのように機能するか見てみましょう。
@SpringJUnitWebConfig(SpringJUnitWebConfigIntegrationTest.Config.class)
public class SpringJUnitWebConfigIntegrationTest {
@Configuration
static class Config {
}
}
@SpringJUnitConfigと同様に、the configuration classes go in the value attributeおよびすべてのリソースは、locations属性を使用して指定されます。
また、@WebAppConfigurationのvalue属性は、resourcePath属性を使用して指定する必要があります。 By default, this attribute is set to “src/main/webapp”.
ここで、WebApplicationContextが実際にロードされたことを確認しましょう。
@Autowired
private WebApplicationContext webAppContext;
@Test
void givenWebAppContext_WhenInjected_ThenItShouldNotBeNull() {
assertNotNull(webAppContext);
}
ここでも、@SpringJUnitWebConfigを使用しない同等のコードがあります。
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration(classes = SpringJUnitWebConfigIntegrationTest.Config.class)
4. 結論
この簡単なチュートリアルでは、Spring 5で新しく導入された@SpringJUnitConfigおよび@SpringJUnitWebConfigアノテーションの使用方法を示しました。
例の完全なソースコードは、over on GitHubで入手できます。