【发布时间】:2019-04-26 10:12:51
【问题描述】:
我有一个consumer.properties 文件,在src/main/resources 中有以下内容,以及一个将文件内容加载并存储到类成员变量中的配置类:
//consumer.propertiessrc/main/resources中的文件:
com.training.consumer.hostname=myhost
com.training.consumer.username=myusername
com.training.consumer.password=mypassword
//ConsumerConfig.java
@Configuration
@PropertySource(
value= {"classpath:consumer.properties"}
)
@ConfigurationProperties(prefix="com.training.consumer")
public class ConsumerConfig {
private String hostname;
private String username;
private String password;
public ConsumerConfig() { }
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "ConsumerConfig [hostname=" + hostname + ", username=" + username + ", password=" + password + "]";
}
}
我还有一个 ConfigsService 类,它自动连接 ConsumerConfig 类来检索各个属性:
@Component
public class ConfigsService {
@Autowired
ConsumerConfig consumerConfig;
public ConsumerConfig getConsumerConfig() {
return consumerConfig;
}
public void showConfig() {
consumerConfig.toString();
}
public ConsumerConfig getConfig() {
return consumerConfig;
}
}
在运行 ConfigsService 的方法时,属性加载得很好。问题出在单元测试中,其中调用configService.getConfig().getHostname() 会返回一个空值——即使在创建了src/test/resources 目录并在其中添加了我的consumer.properties 文件之后:
@TestPropertySource("classpath:consumer.properties")
public class ConfigsServiceTest {
@Mock
ConsumerConfig consumerConfig;
@InjectMocks
ConfigsService configService;
@Before
public void beforeEach() {
MockitoAnnotations.initMocks(this);
}
@Test
public void someTest() {
System.out.println(configService.getConfig().getHostname()); //outputs null here -- wth!
Assert.assertTrue(true);
}
}
【问题讨论】:
-
嗨,你是用 spring runner 运行这个,否则你不会在测试期间启动 spring 实例?
标签: java spring spring-boot properties