gpt4 book ai didi

java - 将基于配置文件的属性文件解析为 Spring 测试

转载 作者:行者123 更新时间:2023-11-30 08:33:35 24 4
gpt4 key购买 nike

在我的 spring RootConfig 类中,我使用基于我的 spring 配置文件的属性文件:

@Configuration
@PropertySource("classpath:properties/app.properties")
@PropertySource("classpath:properties/app-${spring.profiles.active}.properties")
@ComponentScan(...)
public class RootConfig {

@Bean // just because you will ask about it
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}

}

现在我想编写使用这种配置的测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RootConfig.class)
public class RootConfigTest {

@Test
public void testContext() throws Exception {
assertTrue(true);
}

}

但是我的上下文启动失败:java.lang.IllegalStateException: Failed to load ApplicationContext because

无法解析字符串值“classpath:properties/app-${spring.profiles.active}.properties”中的占位符“spring.profiles.active”

这是 web 应用程序,所以最初我的 spring 配置文件配置在:

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.setInitParameter("spring.profiles.active", getSpringProfilesActive());
}

}

getSpringProfilesActive() - 是一个静态方法,它读取系统属性而不依赖于上下文。

最佳答案

在您的情况下,servletContext.setInitParameter("spring.profiles.active", "dev") 被设置为 WebAppInitializer 的一部分,当您运行您的测试用例,在调用测试之前将 spring.profiles.active 设置为 dev,如下所示:

import java.util.Properties;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RootConfig.class)
public class RootConfigTest {

@BeforeClass
public static void setSystemProperty() {
Properties properties = System.getProperties();
properties.setProperty("spring.profiles.active", "dev");
}

@Test
public void testContext() throws Exception {
assertTrue(true);
}

}

关于java - 将基于配置文件的属性文件解析为 Spring 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39385493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com