[英]Spring Boot autowire configuration class into Junit Test
I currently run into a problem with Junit testing in Spring Boot.我目前在 Spring Boot 中遇到了 Junit 测试的问题。 I have an
@Configuration
class for which I want to test the @Bean
methods.我有一个
@Configuration
类,我想为其测试@Bean
方法。 Because these methods are skipped during tests, I extracted the content of the configuration method to a protected method which will then be called inside the @Bean
method of the @Configuration
class.因为这些方法在测试过程中会被跳过,所以我将配置方法的内容提取到一个受保护的方法中,然后在
@Configuration
类的@Bean
方法中调用该方法。 I did that so I can test the behaviour of the methods.我这样做是为了测试这些方法的行为。 Inside this method different
@ConfigurationProperties
are used to load some setups.在此方法中,不同的
@ConfigurationProperties
用于加载一些设置。
Now, in my ConfigurationTest
class, I am mocking the ConfigurationProperties
classes so I can test the correct behaviour of the @Bean
method.现在,在我的
ConfigurationTest
类中,我正在@Bean
ConfigurationProperties
类,以便我可以测试@Bean
方法的正确行为。
My problem is, that my Mockito mocks of the ConfigurationProperties
classes always return null, when I am inside the @Bean
method (more specifically inside the protected method that is called from the @Bean method).我的问题是,当我在
@Bean
方法中(更具体地说,在从 @Bean 方法调用的受保护方法中)时,我的ConfigurationProperties
类的 Mockito 模拟总是返回 null。 It feels like there is a problem with how I setup the @Configuration
class.感觉我设置
@Configuration
类的方式有问题。 Currently I am autowiring it.目前我正在自动装配它。
My question now is, how do I setup the @Configuration
class correctly, so I can call its functions and mock the return values of the there used @ConfigurationProperties
classes?我现在的问题是,如何正确设置
@Configuration
类,以便我可以调用它的函数并模拟使用的@ConfigurationProperties
类的返回值?
Thanks in advance!提前致谢!
Add @EnableConfigurationProperties(value=YourConfigurationProperties.class)
to your test class.将
@EnableConfigurationProperties(value=YourConfigurationProperties.class)
添加到您的测试类。 This will load the properties.这将加载属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.