繁体   English   中英

为什么在春季启动应用程序的Junit测试中无法使用appliction.properties中的属性?

[英]why properties from appliction.properties not available in Junit test in spring boot application?

我有一个Spring Boot应用程序。 我正在写Junit测试。 我试图从application.properties(在src / main / resources / application.properties中定义)和在AppConfig中配置的Status Bean(src / main / java / hello / AppConfig.java)中注入值。 我看到该bean是自动装配的(通过调试器它不是null),但是没有设置值。

这是application.properties

src / main / resources / application.propertie

app.name=rest-service
app.version=1.0.0-SNAPSHOT

src / main / java / hello / AppConfig.java

@Configuration
public class AppConfig {

    @Value("${app.version}")
    private String version;
    @Value("${app.name}")
    private String name;


    @Bean
    public Status status(){
        return new Status(name,version);
    }

}

//状态是带有名称和版本字段的简单pojo

src / test / java / hello / GreetingControllerTests.java

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@ContextConfiguration(classes={hello.TestConfig.class,hello.AppConfig.class})
@WebAppConfiguration
public class GreetingControllerTests {


    @Autowired
    Environment envi;

    @Autowired
    Status status;

    @Value("${app.name:notConfigured}")
    String appName;

    private String env;

    @Before
    public void init(){
        System.out.println(status.getName());
        System.out.println(appName);
        env=envi.getActiveProfiles()[0];
    }

    @Test
    public void should_fail(){
        if (env.equalsIgnoreCase("DEV")){
            assertThat(false).isFalse();
        }
        if (env.equalsIgnoreCase("QA1")){
            System.out.println("failing the test");
            fail();
        }
    }
}

我在init方法中设置了调试器,发现没有注入正确设置了值的appNamestatus bean。 但是,状态豆被注入。 只是没有设置值。

感谢您分享项目。 它使工作变得更加容易。 请查看我的请求请求(带有注释)以了解我如何使其全部正常工作。

https://bitbucket.org/SpringDevSeattle/gs-rest-service/pull-requests/4/updating-project-for-spring-boot-14/diff

*更新*由于将一些旧的Spring注释与更新的注释混合在一起,因此您的注释被覆盖了。 归功于不是@Autowired的spring-boot属性 ,它基于Google搜索application.properties not being populated in the environment为我提供解决方案。

如果您查看@SpringApplicationConfiguration

@ContextConfiguration(loader = SpringApplicationContextLoader.class)
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Deprecated
public @interface SpringApplicationConfiguration {

它实际上由许多其他注释组成。 重要的是@ContextConfiguration 对于@SpringApplicationConfiguration它使用一个加载器,并且该加载器正在扫描类路径以查找适当的配置文件以及要加载的组件(其中一个是将application.properties读取到环境中的东西)。 在测试中,您可以使用声明覆盖该注释:

@ContextConfiguration(classes={hello.TestConfig.class,hello.AppConfig.class})

这迫使Spring只加载TestConfig和AppConfig类,而不扫描其他任何配置文件。 注释掉该注释并运行它将使测试通过,并调试init()方法将显示注入的值。

在测试下的资源目录中,您需要另一个属性文件。

/src/test/resources

那就是junit正在寻找的地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM