且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Spring Boot 测试中正确使用 TestPropertyValues

更新时间:2022-01-08 01:01:38

TestPropertyValues 在设计时并未真正考虑 @SpringBootTest.当您编写手动创建 ApplicationContext 的测试时,它会更有用.如果您真的想将它与 @SpringBootTest 一起使用,应该可以通过 ApplicationContextInitializer 来实现.像这样:

TestPropertyValues isn't really designed with @SpringBootTest in mind. It's much more useful when you are writing tests that manually create an ApplicationContext. If you really want to use it with @SpringBootTest, it should be possible to via an ApplicationContextInitializer. Something like this:

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(initializers = PropertyTest.MyPropertyInitializer.class)
public class PropertyTest {

    @Autowired
    private ApplicationContext context;

    @Test
    public void test() {
        assertThat(this.context.getEnvironment().getProperty("foo")).isEqualTo("bar");
    }

    static class MyPropertyInitializer
            implements ApplicationContextInitializer<ConfigurableApplicationContext> {

        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            TestPropertyValues.of("foo=bar").applyTo(applicationContext);
        }

    }

}

Spring Boot 自己的测试大量使用了 TestPropertyValues.例如,applyToSystemProperties 在您需要设置系统属性并且不希望它们在测试完成后意外留下时非常有用(参见 EnvironmentEndpointTests 的例子).如果您搜索代码库,您会发现很多其他关于它通常使用的方式的示例.

Spring Boot's own test make use of TestPropertyValues quite a bit. For example, applyToSystemProperties is very useful when you need to set system properties and you don't want them to be accidentally left after the test finishes (See EnvironmentEndpointTests for an example of that). If you search the codebase you'll find quite a few other examples of the kinds of ways it usually gets used.