繁体   English   中英

获取在 Junit 中自动装配的 @ConfigurationProperties bean

[英]Get @ConfigurationProperties bean autowired in Junit

在此处输入代码我有一个 class 在 spring 启动中用 @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 显示为 null --

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

如果您想专门测试您的配置,请使用 @TestConfiguration 注释。 There are two ways of using the annotation Either on a static inner class in the same test class where we want to @Autowire the bean or create a separate test configuration class:

我将在 static class 中选择第一个选项

见下面的例子,

@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
 }

//好吧,这行得通,现在还有另一个像下面这样的 class 是测试的一部分,configClass 没有在那里自动装配,有什么想法

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

@TestConfiguration
public YourTestConfigurationClass ()
{
// plus all the other code which worked 

    @Component
    public class OtherClass{
 
      @Autowired
      private ConfigClass configClass;
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM