【问题标题】:Testing that custom Spring Boot AutoConfiguration is valid测试自定义 Spring Boot AutoConfiguration 是否有效
【发布时间】:2016-08-30 11:13:27
【问题描述】:

我决定编写一个非常简单的测试来检查我的 Spring Boot 自动配置是否有效 - 所有需要的 bean 都连同它们的依赖关系一起创建。

自动配置是:

package org.project.module.autoconfigure;

import org.project.module.SomeFactory;
import org.project.module.SomeProducer;
import org.project.module.SomeServiceClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Spring Boot simple auto-configuration.
 *
 * @author istepanov
 */
@Configuration
@ComponentScan("org.project.module.support")
public class SomeAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public SomeFactory someFactory() {
        return new SomeFactory();
    }

    @Bean
    @ConditionalOnMissingBean
    public SomeServiceClient someServiceClient() {
        return new SomeServiceClient();
    }

    @Bean
    @ConditionalOnMissingBean
    public SomeProducer someProducer() {
        return new SomeProducer();
    }
}

测试是:

package org.project.module.autoconfigure;

import org.project.module.SomeFactory;
import org.project.module.SomeProducer;
import org.project.module.SomeServiceClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@code SomeAutoConfiguration}.
 *
 * @author istepanov
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {SomeAutoConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class SomeAutoConfigurationTest {

    @Autowired
    private SomeFactory someFactory;
    @Autowired
    private SomeServiceClient someServiceClient;
    @Autowired
    private SomeProducer someProducer;

    @Test
    public void someFactory_isNotNull() {
        assertThat(someFactory).isNotNull();
    }

    @Test
    public void someServiceClient_isNotNull() {
        assertThat(someServiceClient).isNotNull();
    }

    @Test
    public void someProducer_isNotNull() {
        assertThat(someProducer).isNotNull();
    }
}

但实际上测试因异常而失败 - 预计将使用 @ComponentScan 加载的依赖 bean 实际上丢失了:

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener.prepareTestInstance(AutoConfigureReportTestExecutionListener.java:49)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someFacade': Unsatisfied dependency expressed through method 'setSomeMetrics' parameter 0: Error creating bean with name 'someMetrics': Unsatisfied dependency expressed through method 'setCounterService' parameter 0: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someMetrics': Unsatisfied dependency expressed through method 'setCounterService' parameter 0: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:648)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 22 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someMetrics': Unsatisfied dependency expressed through method 'setCounterService' parameter 0: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:648)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 40 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 54 more

任何想法我错过了什么?

P.S.:还添加了缺少的 SomeMetrics:

package org.project.module.support.metrics;

import org.project.module.support.SomeProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import static org.mockito.Mockito.mock;

/**
 * Customization for Spring Actuator, defines application-specific counters and metrics.
 *
 * @author istepanov
 */
@Component
public class SomeMetrics {

    @Value("${const.metrics.some.connections.current:some.connections.created}")
    private String connectorsCurrent;
    @Value("${const.metrics.some.connections.idle:some.connections.idle}")
    private String connectorsIdle;
    @Value("${const.metrics.some.connections.max:some.connections.max}")
    private String connectorsMax;

    private CounterService counterService;
    private GaugeService gaugeService;
    private SomeProperties someProperties;

    @Autowired
    public void setSomeProperties(SomeProperties someProperties) {
        this.someProperties = someProperties;
    }

    @Autowired
    public void setCounterService(CounterService counterService) {
        this.counterService = counterService;
    }

    @Autowired
    public void setGaugeService(GaugeService gaugeService) {
        this.gaugeService = gaugeService;
    }

    /**
     * Use mocks for {@link CounterService} and {@link GaugeService} if CRMBO is not configured properly.
     */
    @PostConstruct
    public void init() {
        if (someProperties.isMock()) {
            counterService = mock(CounterService.class);
            gaugeService = mock(GaugeService.class);
        }
    }

    public void decrementConnectorsCurrent() {
        this.counterService.decrement(connectorsCurrent);
    }

    public void incrementConnectorsCurrent() {
        this.counterService.increment(connectorsCurrent);
    }

    public void decrementConnectorsIdle() {
        this.counterService.decrement(connectorsIdle);
    }

    public void incrementConnectorsIdle() {
        this.counterService.increment(connectorsIdle);
    }

    public void decrementConnectorsMax() {
        this.counterService.decrement(connectorsMax);
    }

    public void incrementConnectorsMax() {
        this.counterService.increment(connectorsMax);
    }
}

【问题讨论】:

  • 如果删除其中一个 bean 上的 @ConditionalOnMissingBean 注释会发生什么?
  • 无变化 - 相同的例外。
  • 据我了解,代码@ComponentScan("org.project.module.support") 被忽略,因此不会创建低级bean。
  • 我们可以查看您的 POM 或 Gradle 文件吗?错误消息提到了someMetricscounterService 之类的东西,它们似乎都与您的自动配置无关。除非您在示例代码中更改了名称,但没有在堆栈跟踪中更改名称?
  • 这是自定义的自动配置。我开发了一个供企业使用的小型库,并决定将其设为“自动配置”。所以现在我想用测试来覆盖这个自定义配置——只是为了确保创建了所有需要的 bean。问题来了。

标签: java spring-boot integration-testing


【解决方案1】:

为什么不从 Spring Boot 自己的一些自动配置类测试中汲取灵感呢?例如,JacksonAutoConfigurationTests

当您测试自动配置类时,您通常希望在上下文中使用不同的 bean 和配置属性进行测试,以便您可以验证任何 @ConditionalOnMissingBean@ConditionalOnProperty 注释是否按预期工作。出于这个原因,测试不使用@SpringBootTest 或 Spring Framework 的测试框架,后者要求类中的每个测试都使用相同的应用程序上下文。

我也会避免在自动配置类中使用@ComponentScan。 Spring Boot 的自动配置都没有使用它。相反,您的自动配置应该通过 @Bean 方法定义所有组件,或者分别使用 @Import@ImportResource 导入其他基于 Java 和 XML 的配置。

【讨论】:

  • 谢谢,我刚刚尝试了最简单的方法,它奏效了 :) 有罪。但我会摆脱@ComponentScan - 很可能会解决问题。
  • 提出对 Spring Boot 的小改进:github.com/spring-projects/spring-boot/issues/6794
  • 这条评论为我指明了正确的方向,并在此过程中学到了很多东西。
【解决方案2】:

在我看来,这更像是一个常规的 Spring 配置问题,不一定是 Spring Boot 自动配置问题。

在您的测试中,您只配置了SomeAutoConfiguration 来初始化您的应用程序上下文,并且由于@ComponentScan 注释,它会发现其他要设置的组件,例如SomeMetricsSomeMetrics 依赖于某些 Spring Boot Actuator bean 的存在,由于测试中的上下文配置狭窄,它们并不存在。

如果你想让事情正常工作,你必须在上下文中添加更多的 bean,或者向你的 SomeMetrics 组件添加一些条件以防止它被创建,除非存在必要的 bean,如下所示:

@Component
@ConditionalOnBean({CounterService.class, GaugeService.class})
public class SomeMetrics {

    // Content ommitted for brevity.
}

我不知道哪种解决方案更适合您的情况。

【讨论】:

  • 感谢@ThomasKåsene 的建议。我将尝试按照@AndyWilkinson 的建议创建所有 bean,并且肯定会使用 @ConditionalOnBean
  • 但实际上我认为@ConditionalOnBean是用来确定是否应该创建bean,而不是用于排序。由于在实例化所有 bean 后执行注入,这应该不是问题。
  • 用于确定是否应该创建bean。我的意思是你的上下文甚至不包含SomeMetrics 需要的任何bean,因为你的测试没有设置它们。虽然我同意您应该手动创建所有 bean 以进行自动配置,但我认为这不是本例中问题的根源。
  • 是的,我的错,现在我明白你的意思了。实际上,我希望 Spring Boot 能够处理其 bean 的创建。似乎 Actuator 不知何故丢失了 - 无论如何我想让它成为可选的,所以我会试试这个,谢谢!
猜你喜欢
  • 2021-07-30
  • 2014-12-29
  • 2022-01-04
  • 2017-06-21
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2020-05-20
  • 2017-12-03
相关资源
最近更新 更多