在SpringBoot测试中获取配置属性类Bean

问题描述 投票:0回答:1

我定义了一个类来自动加载我的springboot applicaton-*.properties中的属性。

@Component
@ConfigurationProperties("my-app")
@EnableConfigurationProperties
@Data
public class MyAppProperties {

  private String propertyX;
  private String propertyY;

..

}

现在这里是我的测试类

@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class MessageProcessorApplicationTests {

  @Autowired
  private static RestTemplate restTemplate;

  @Autowired
  public static MyAppProperties myAppProperties;

  @Test
  public void testSomething(){
     doSomeSeetup(myAppProperties.getPropertyX()) //myAppProperties is null!! why?
}

在我的测试中,myAppProperties总是空的。我如何在测试中获得这个实例?

java spring spring-boot spring-test spring-boot-test
1个回答
2
投票

注释 MessageProcessorApplicationTests@RunWith(SpringRunner.class) 自动加载应用程序.属性文件

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class MessageProcessorApplicationTests {

@Autowired
  private static RestTemplate restTemplate;

  @Autowired
  public static MyAppProperties myAppProperties;

  @Test
  public void testSomething(){
     doSomeSeetup(myAppProperties.getPropertyX());

}

0
投票

添加 @EnableConfigurationProperties(value = MyAppProperties.class) 到你的测试类。

@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@EnableConfigurationProperties(value = MyAppProperties.class)
public class MessageProcessorApplicationTests {

  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  public MyAppProperties myAppProperties;

  @Test
  public void testSomething(){
     doSomeSeetup(myAppProperties.getPropertyX()) //myAppProperties is null!! why?
}
© www.soinside.com 2019 - 2024. All rights reserved.