【问题标题】:Passing decisional param to @TestConfiguration class将决策参数传递给 @TestConfiguration 类
【发布时间】:2023-03-29 22:38:02
【问题描述】:

我想在@TestConfiguration 类中向@Bean 发送一个参数,以返回不同的AnimalType,具体取决于参数中的字符串。是否可以从测试课程中完成,或者我需要为每个课程设置不同的配置?

@TestConfiguration
public class TestConfig {

       @Bean
       public AnimalType componentType(String type) {
          return new AnimalType(type);
       }

}

也可以通过构造注入来实现,但也不能使用非 bean 的参数调用 @TestConfig 构造函数;

【问题讨论】:

    标签: java spring-boot testing


    【解决方案1】:

    您可以从这样的属性中读取type

    @Component
    public class AnimalType {
    
        @Value("${animal.type}")
        private String value;
    }
    

    然后在您的测试中使用@SpringBootTest(properties = { "animal.type=dog" }) 指定它。

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      相关资源
      最近更新 更多