【问题标题】:Get @ConfigurationProperties bean autowired in Junit获取在 Junit 中自动装配的 @ConfigurationProperties bean
【发布时间】:2022-01-03 11:21:29
【问题描述】:

在此处输入代码我在 Spring Boot 中有一个用 @ConfigurationProperties 注释的类,如何在 Junit 测试中自动装配这个 bean

@ConfigurationProperties
 public class ConfigClass{
   public String property;
}

--正在测试中--

@RunWith(MockitoJunitRuner.class)
 class MyTests{

 @Autowired
 private ConfigClass configClass;

 @Test
 public myTest1(){
   String prop = configClass.getProperty();
   //Some assert
 }

-- 当我运行这个测试时,configClass 显示为空--

【问题讨论】:

    标签: java spring-boot junit4


    【解决方案1】:

    使用 jUnit 测试 springboot,您可以使用 @RunWith(SpringRunner.class) 或 @SpringbootTest 来加载整个上下文

    如果您想专门测试您的配置,请使用 @TestConfiguration 注解。有两种使用注解的方法,要么在我们想要 @Autowire bean 的同一测试类中的静态内部类上,要么创建一个单独的测试配置类:

    我会选择静态类中的第一个选项

    见下面的例子,

    @ConfigurationProperties
     public class ConfigClass{
       public String property;
    }
    --Now under Test--
    
    @RunWith(MockitoJunitRuner.class)
     class MyTests{
    
    
     @Autowired
     private ConfigClass configClass;
    
    **// here use the @TestConfiguration annotation not @Test**
    
     @TestConfiguration
     public myTest1(){
       String prop = configClass.getProperty();
       //Some assert
     }
    

    //好的,现在有另一个像下面这样的类是测试的一部分,configClass 没有在那里自动装配,任何想法

    注意:我建议使用第二个选项,即具有单独的测试配置类来自动装配类中的所有配置,如下所示

    @TestConfiguration
    public YourTestConfigurationClass ()
    {
    // plus all the other code which worked 
    
        @Component
        public class OtherClass{
     
          @Autowired
          private ConfigClass configClass;
       }
    }
    

    【讨论】:

    • 我能够在 Junits 中获取组件和资源库 bean,但不能在 Configurationproperties 中获取
    • @KiranChannayanamath 你能显示你的代码吗?
    • 我已经编辑了帖子,请找到代码。 @艾哈迈德霍斯尼
    • 我已经更新了我的答案,请检查它是否适合你
    • 是的,可以,但是我在您的代码中提到了另一个警告,请您检查一下,抱歉,我的原始帖子@AhmedHosny 中没有提到。
    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 2018-02-28
    • 2019-04-04
    • 2014-03-11
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多