我有一个consumer.properties
文件,该文件在src/main/resources
中具有以下内容,以及一个随附的Configuration类,该类将文件的内容加载并存储到类成员变量中:
// consumer.properties
文件在src/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()
时会抛出NPE -即使在创建了src/test/resources
目录,在其中添加我的consumer.properties
文件并自动在测试:
@TestPropertySource("classpath:consumer.properties")
public class ConfigsServiceTest {
@Autowired
ConsumerConfig consumerConfig;
@InjectMocks
ConfigsService configService;
@Before
public void beforeEach() {
MockitoAnnotations.initMocks(this);
}
@Test
public void someTest() {
System.out.println(configService.getConfig().getHostname()); //Throws Null Pointer Exception here.
Assert.assertTrue(true);
}
}