简体   繁体   English

Spring Boot 将配置类自动装配到 Junit 测试中

[英]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.

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