Java @TestPropertySource 不适用于 Spring 1.2.6 中使用 AnnotationConfigContextLoader 的 JUnit 测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32633638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:53:10  来源:igfitidea点击:

@TestPropertySource doesn't work for JUnit test with AnnotationConfigContextLoader in Spring 1.2.6

javaspringjunitspring-boot

提问by Thomas Beauvais

It doesn't seem that anything I do in Spring 4.1.17 with Spring Boot 1.2.6.RELEASE works at all. I just want to access the application properties and override them with test if necessary (without using the hack to inject a PropertySource manually)

我在 Spring 4.1.17 中使用 Spring Boot 1.2.6.RELEASE 所做的任何事情似乎都不起作用。我只想访问应用程序属性并在必要时用测试覆盖它们(不使用 hack 手动注入 PropertySource)

this doesn't work..

这不起作用..

@TestPropertySource(properties = {"elastic.index=test_index"})

nor does this..

这也不..

@TestPropertySource(locations = "/classpath:document.properties")

nor this..

也不是这个..

@PropertySource("classpath:/document.properties")

full test case..

完整的测试用例..

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@TestPropertySource(properties = {"elastic.index=test_index"})
public class PropertyTests {
    @Value("${elastic.index}")
    String index;

    @Configuration
    @TestPropertySource(properties = {"elastic.index=test_index"})
    static class ContextConfiguration {
    }

    @Test
    public void wtf() {
        assertEquals("test_index", index);
    }
}

resulting in

导致

org.junit.ComparisonFailure: 
Expected :test_index
Actual   :${elastic.index}

It seems there is a lot of conflicting information between 3.x and 4.x and I can't find anything that will work for sure.

似乎 3.x 和 4.x 之间有很多相互矛盾的信息,我找不到任何可以肯定有效的信息。

Any insight would be gratefully appreciated. Cheers!

任何见解将不胜感激。干杯!

采纳答案by Thomas Beauvais

Turns out the best way (until Spring fixes this oversight) is to a PropertySourcesPlaceholderConfigurerthat will bring in test.properties (or whatever you want) and @Importor extend that @Configuration.

事实证明,最好的方法(直到 Spring 修复此疏忽)是PropertySourcesPlaceholderConfigurer将引入 test.properties(或任何您想要的)和@Import或扩展它的@Configuration.

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

@Configuration
public class PropertyTestConfiguration {
    @Bean
    public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() throws IOException {
        final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocations(ArrayUtils.addAll(
                        new PathMatchingResourcePatternResolver().getResources("classpath*:application.properties"),
                        new PathMatchingResourcePatternResolver().getResources("classpath*:test.properties")
                )
        );

        return ppc;
    }

}

This allows you to define defaults in application.properties and override them in test.properties. Of course, if you have multiple schemes, then you can configure the PropertyTestConfigurationclass as necessary.

这允许您在 application.properties 中定义默认值并在 test.properties 中覆盖它们。当然,如果您有多个方案,那么您可以PropertyTestConfiguration根据需要配置该类。

And use this in a unit test.

并在单元测试中使用它。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class PropertyTests {
    @Value("${elastic.index}")
    String index;

    @Configuration
    @Import({PropertyTestConfiguration.class})
    static class ContextConfiguration {
    }
}

回答by user2004685

Have you tried using @PropertySource("classpath:document.properties")or @PropertySource("classpath*:document.properties")?

你试过使用@PropertySource("classpath:document.properties")@PropertySource("classpath*:document.properties")吗?

回答by Don Bottstein

Your use of @Value requires a PropertySourcesPlaceholderConfigurer bean to resolve ${...}placeholders. See the accepted answer here: @Value not set via Java-configured test context

您对 @Value 的使用需要一个 PropertySourcesPlaceholderConfigurer bean 来解析${...}占位符。请参阅此处接受的答案:@Value not set via Java-configured test context

回答by sorrymissHymanson

I used the locationsproperty of @TestPropertySourceto override (or add) properties.

我使用了 的locations属性@TestPropertySource来覆盖(或添加)属性。

This worked for me (spring 4.2.4):

这对我有用(春季 4.2.4):

@TestPropertySource(locations = {
   "classpath:test.properties",
   "classpath:test-override.properties" })

But overriding properties like below didn't:

但是像下面这样的覆盖属性没有:

@TestPropertySource(
  locations = {"classpath:test.properties"},
  properties = { "key=value" })

Even though the javadoc says that those properties have highest precedence. A bug maybe?

即使 javadoc 说这些属性具有最高优先级。也许是一个错误?

Update

更新

The bug should be fixed in Spring boot version 1.4.0 and up. See the commit which closes the issue. By now, properties declared in the presented way should get precedence.

该错误应在 Spring boot 1.4.0 及更高版本中修复。查看关闭问题提交。现在,以呈现方式声明的属性应该优先。

回答by Swarit Agarwal

For Me @TestPropertySource("classpath:xxxxxxxx.properties") worked

对我来说@TestPropertySource("classpath:xxxxxxxx.properties") 有效

回答by S.Sriniavasulu

I had issue with @TestPropertySource. test.properties not found

我对@TestPropertySource 有问题。未找到 test.properties

below is the one before fixed

下面是修复前的

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ExtContext.class)
@TestPropertySource(locations = "classpath: test.properties")

i removed space between classpath: and test.properties as below

我删除了 classpath: 和 test.properties 之间的空间,如下所示

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ExtContext.class)
@TestPropertySource(locations = "classpath:test.properties")

This worked for me, When test.properties is not found in classpth. misht work for you aswell

这对我有用,当在 classpth 中找不到 test.properties 时。也适合你

回答by goldlil

If you have this problem and you're trying with yaml as properties file keep in mind that spring @TestPropertySourceand @PropertySourcedoesn't work with yaml file, and properties won't be loaded properly.

如果您遇到此问题并且您正在尝试使用 yaml 作为属性文件,请记住 spring@TestPropertySource并且@PropertySource不适用于 yaml 文件,并且属性将无法正确加载。

https://github.com/spring-projects/spring-boot/issues/10772#issuecomment-339581902

https://github.com/spring-projects/spring-boot/issues/10772#issuecomment-339581902