我有一个 consumer.properties
文件,在 src/main/resources
中包含以下内容,以及一个随附的 Configuration 类,该类将文件的内容加载并存储到类成员中变量:
//src/main/resources
中的consumer.properties
文件:
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
类,它 Autowiring ConsumerConfig
类以检索各个属性:
@Component
public class ConfigsService {
@Autowired
ConsumerConfig consumerConfig;
public ConsumerConfig getConsumerConfig() {
return consumerConfig;
}
public void showConfig() {
consumerConfig.toString();
}
public ConsumerConfig getConfig() {
return consumerConfig;
}
}
运行 ConfigsService 的方法时,属性加载得很好。问题出在单元测试中,即使在创建了 src/test/resources 目录之后,调用 configService.getConfig().getHostname() 也会返回空值,并在其中添加我的 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,它将加载配置类中的属性并创建 bean。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ConsumerConfig.class, ConfigsService.class})
@TestPropertySource(locations = "classpath:consumer.properties")
public class ConfigsServiceTest {
@Autowired
private ConfigsService configsService;
@Test
public void someTest() {
Assert.assertNotNull(configService.getConfig().getHostname());
}
}
关于java - Spring Boot - Junit 无法在 junit 测试中加载配置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53452777/