Java Spring Boot 单元测试未检测到自动装配组件的模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51069050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:56:14  来源:igfitidea点击:

Spring Boot Unit Test a module not detecting an autowired component

javaspring-bootintellij-ideaspring-boot-test

提问by Carmageddon

we have split our Maven based Spring Boot project into two modules as follows:

我们将基于 Maven 的 Spring Boot 项目拆分为两个模块,如下所示:

ProjectRoot
-SharedModel
-Application
--main
---java
----com....(Application.java)
-----com....(ClassToAutowire.java)
--test
----com....(ApplicationTest.java)
-----com....(ClassToAutowireTest.java)

The test class looks as follows:

测试类如下所示:

@RunWith(SpringRunner.class)
public class ClassToAutowireTest extends BaseTest {

    @Autowired
    private ClassToAutowire classToAutowire;

    @Before
    public void setup() throws IOException {        
    ....
    }

    @Test
    public void someTest() {
        ....
        assertEquals(this.classToAutowire.isSupported(this.message), true);
    }

}

The ClassToAutowire looks like the follows:

ClassToAutowire 如下所示:

@Component
public class ClassToAutowire {

    private ConfigurationService configurationService;

    @Autowired
    public ClassToAutowire(ConfigurationService configurationService) {
        this.configurationService = configurationService;
    }



    ....

}

The Application.java looks as follows:

Application.java 如下所示:

@SpringBootApplication
@EnableRetry
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

And the ApplicationTest.java looks as follows:

ApplicationTest.java 如下所示:

@SpringBootTest
@RunWith(SpringRunner.class)
public class ApplicationTests {

    @Test
    @Ignore
    public void contextLoads() {
        // °o¤?,??,?¤o°`°o¤?,?,?¤°o¤?,??,?¤o°`°o¤?,?
    }
}

When I run this Unit Test, we get the following trace:

当我运行这个单元测试时,我们得到以下跟踪:

    2018-06-27 15:02:37.835 ERROR [                                main] context.TestContextManager.prepareTestInstance(TestContextManager.java:234): Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@57c03d88] to prepare test instance [com.some.package.structure.ClassToAutowireTest@16aa8654]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.some.package.structure.ClassToAutowireTest': Unsatisfied dependency expressed through field 'classToAutowire'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.some.package.structure.ClassToAutowire' 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:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:386)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    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.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.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access
--/test
--/--/java
--/--/--/com
--/--/--/--/TestClass
0(ParentRunner.java:58) at org.junit.runners.ParentRunner.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.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.NoSuchBeanDefinitionException: No qualifying bean of type 'com.some.package.structure.ClassToAutowire' 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:1493) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ... 27 more

Looks like this problem can be bypassed by adding the annotation @SpringBootTest(classes={ClassToAutowire.class})below the @RuneWithannotation, but then the unit test seems to load the whole SpringBoot app to run test.

看起来这个问题可以通过在注释@SpringBootTest(classes={ClassToAutowire.class})下面添加注释来绕过 @RuneWith,但是单元测试似乎加载了整个 SpringBoot 应用程序来运行测试。

My questions are:

我的问题是:

1) Why is this extra annotation needed to workaround the problem? It is supposed to scan the entire Application/main/java/.... (based on Application.java), so why is it not detecting the component?

1)为什么需要这个额外的注释来解决这个问题?它应该扫描整个Application/main/java/....(基于Application.java),为什么它没有检测到组件?

2) How best to do it, with minimal loading to make unit tests faster?

2)如何最好地做到这一点,以最小的负载使单元测试更快?

采纳答案by Pospolita Nikita

Provide your test with @ContextConfiguration(classes = ClassToAutowire.class), then your context will be provided with that class. @SpringBootTestannotation is used in Integration Tests to load full context. With @ContextConfigurationannotation you are able to load only part of context.

为您的测试提供@ContextConfiguration(classes = ClassToAutowire.class),然后您的上下文将与该类一起提供。@SpringBootTest集成测试中使用注释来加载完整的上下文。使用@ContextConfiguration注释,您只能加载部分上下文。

回答by ISlimani

@SpringBootTestis used for integration tests that's mean integrating different layers of the application. This is why it loads the whole context.

@SpringBootTest用于集成测试,这意味着集成应用程序的不同层。这就是它加载整个上下文的原因。

If you want to unit test only controllers, use @WebMvcTestand mockall the other layers that you need.

如果您只想对控制器进行单元测试,请使用@WebMvcTest模拟您需要的所有其他层。

For full unit tests of all the layers with working examples see: Testing in Spring

有关带有工作示例的所有层的完整单元测试,请参阅: 在 Spring 中测试

Last date of retrieval: 2018/27/06

最后检索日期:2018/27/06

回答by Kamil Naja

I'have resolved this error, by move my test class into the com package. Structure of test folder looks like this

我已经解决了这个错误,将我的测试类移到了 com 包中。测试文件夹的结构如下所示

##代码##

I'm not sure, if this structure is ok, but this works.

我不确定这个结构是否可以,但这是有效的。