Java 如何在测试中@autowiredbuildproperties?

Java 如何在测试中@autowiredbuildproperties?,java,spring,maven,Java,Spring,Maven,我正在使用此批注在我的应用程序中显示生成版本: @Autowired BuildProperties buildProperties; ... log.info("Startup finish - {}", buildProperties.getVersion()); 使用此maven插件: <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin<

我正在使用此批注在我的应用程序中显示生成版本:

@Autowired BuildProperties buildProperties;
...
log.info("Startup finish - {}", buildProperties.getVersion());
使用此maven插件:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
    <executable>true</executable>
</configuration>
<executions>
    <execution>
        <goals>
            <goal>build-info</goal>
        </goals>
我添加文件src/test/resources/META-INF/build-info.properties

但生成仍有错误:

java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    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:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'application': Unsatisfied dependency expressed through field 'buildProperties'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.info.BuildProperties' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1336)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:548)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    ... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.info.BuildProperties' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1506)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:581)
    ... 43 more
如何在测试期间使其工作


解决方案:添加注释@SpringBootTest

无论在测试类中自动连线什么,都必须在测试类中设置。一种方法是使用ReflectionTestUtils

ReflectionTestUtils.setField("yourClass", buildProperties, objBuildProperties)
这里,objBuildProperties是BuildProperties的一个对象,您可以在上面的代码行中实例化并使用它


我还想问你,你到底什么时候得到这个错误的?在运行测试用例时,或者在什么时候?

对我来说,以下工作(我使用的是JUnit 5):

@extendedwith(SpringExtension.class)
注释测试类就足够了,因为测试需要知道BuildProperties bean,您需要使用
@import({BuildProperties.class})

因此,测试类的完整注释可以是:

@ExtendWith(SpringExtension.class)
@DataJpaTest
@Import( {BuildProperties.class })
@ComponentScan("org.yourpackage")
public class MyTestClass {

    @Autowired
    private TodoUserRepository todoUserRepository;

通过这个Spring,您可以自动创建一个BuildProperties bean,只要您自己的类被实例化,它就可以被注入到您的类中。在我的MyTestClass中,我使用@Autowired来实现这一点


要测试的类(真正使用BuildProperties的类在上面的代码段中称为ToDouseRepository)。

您还可以使BuildProperties成为非必需的。像这样:

@Autowired(required = false)    // When building or running unit-tests
// from eclipse or intellij, BuildProperties is not available out of the box.
private BuildProperties buildProperties;

当运行测试时,它将是
null

您可能需要
@TestPropertySource(locations=“classpath:build info.properties”)
在您的测试类上也不起作用:原因:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“org.springframework.boot.info.BuildProperties”类型的合格bean可用:至少需要1个符合autowire候选条件的bean。依赖项注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}您好,我遇到了完全相同的问题。但是我不理解你的解决方案:你在哪里添加了@SpringBootTest?是的,它是在测试启动应用程序上下文时添加的。我在测试中看到了你的台词,但现在已经“太晚了”,因为之前出现过错误没有类型为“org.springframework.boot.info.BuildProperties”的合格bean可用:至少需要1个符合autowire候选资格的bean。我使用以下注释完成了它的工作:@SpringBootTest它似乎在上下文中装载BuildProperties。
@Autowired(required = false)    // When building or running unit-tests
// from eclipse or intellij, BuildProperties is not available out of the box.
private BuildProperties buildProperties;