Аннотации SpringJUnitConfig и SpringJUnitWebConfig в Spring 5

SpringJUnitConfig и SpringJUnitWebConfig Аннотации в Spring 5

1. Вступление

В этой быстрой статье мы рассмотрим новые аннотации@SpringJUnitConfig и@SpringJUnitWebConfig, доступные в Spring 5.

These annotations are a composition of JUnit 5 and Spring 5 annotations, которые упрощают и ускоряют создание тестов.

2. @SpringJUnitConfigс

@SpringJUnitConfig объединяет эти 2 аннотации:

  • @ExtendWith(SpringExtension.class) from JUnit 5 для запуска теста с классомSpringExtension и

  • @ContextConfiguration from Spring Testing для загрузки контекста Spring

Давайте создадим тест и применим эту аннотацию на практике:

@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.

Кроме того, атрибутvalue для@WebAppConfiguration теперь должен быть указан с помощью атрибута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. Заключение

В этом кратком руководстве мы показали, как использовать недавно представленные аннотации@SpringJUnitConfig и@SpringJUnitWebConfig в Spring 5.

Полный исходный код примеров доступенover on GitHub.