Spring 5中的SpringJUnitConfig和SpringJUnitWebConfig批注

The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5

1.简介

在这篇快速文章中,我们将介绍Spring 5中提供的新@SpringJUnitConfig和@SpringJUnitWebConfig批注。

这些注释由JUnit 5和Spring 5注释组成,这些注释使测试创建更加容易和快捷。

2. @SpringJUnitConfig

@SpringJUnitConfig结合了这两个注释:

  • 来自JUnit 5的@ExtendWith(SpringExtension.class)使用SpringExtension类和

  • Spring Testing的@ContextConfiguration加载Spring上下文

  • 让我们创建一个测试并在实践中使用此注释:

    1
    2
    3
    4
    5
    6
    @SpringJUnitConfig(SpringJUnitConfigIntegrationTest.Config.class)
    public class SpringJUnitConfigIntegrationTest {

        @Configuration
        static class Config {}
    }

    请注意,与@ContextConfiguration相比,配置类是使用value属性声明的。但是,应使用locations属性指定资源位置。

    现在我们可以验证Spring上下文是否已真正加载:

    1
    2
    3
    4
    5
    6
    7
    @Autowired
    private ApplicationContext applicationContext;

    @Test
    void givenAppContext_WhenInjected_ThenItShouldNotBeNull() {
        assertNotNull(applicationContext);
    }

    最后,这里我们具有@SpringJUnitConfig(SpringJUnitConfigTest.Config.class)的等效代码:

    1
    2
    @ExtendWith(SpringExtension.class)
    @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class)

    3. @SpringJUnitWebConfig

    @SpringJUnitWebConfig结合了@SpringJUnitConfig的相同批注以及Spring测试中的@WebAppConfiguration-加载WebApplicationContext。

    让我们看看这个注释是如何工作的:

    1
    2
    3
    4
    5
    6
    7
    @SpringJUnitWebConfig(SpringJUnitWebConfigIntegrationTest.Config.class)
    public class SpringJUnitWebConfigIntegrationTest {

        @Configuration
        static class Config {
        }
    }

    与@SpringJUnitConfig一样,配置类位于value属性中,并且使用locations属性指定任何资源。

    另外,现在应该使用resourcePath属性指定@WebAppConfiguration的value属性。默认情况下,此属性设置为" src / main / webapp"。

    现在让我们验证WebApplicationContext是否已真正加载:

    1
    2
    3
    4
    5
    6
    7
    @Autowired
    private WebApplicationContext webAppContext;

    @Test
    void givenWebAppContext_WhenInjected_ThenItShouldNotBeNull() {
        assertNotNull(webAppContext);
    }

    再次,这里我们有等效的代码,而没有使用@SpringJUnitWebConfig:

    1
    2
    3
    @ExtendWith(SpringExtension.class)
    @WebAppConfiguration
    @ContextConfiguration(classes = SpringJUnitWebConfigIntegrationTest.Config.class)

    4。结论

    在这个简短的教程中,我们展示了如何在Spring 5中使用新引入的@SpringJUnitConfig和@SpringJUnitWebConfig批注。

    示例的完整源代码可在GitHub上获得。