测试类中的静态内部类识别不到NoSuchBeanDefinitionException解决

35次阅读

共计 745 个字符,预计需要花费 2 分钟才能阅读完成。

问题

测试类里面的静态内部类识别不到

@RunWith(SpringRunner.class)
@SpringBootTest
public class FooTest {
    @Autowired
    private Bar bar;
    @Test
    public void bar() {}

    @Component
    public static class Bar {}}

但执行 bar 测试方法的时候 报错:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.my.app.dao.FooTest$Bar' 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:1654) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    
    

解决
添加两个额外的注解

@RunWith(SpringRunner.class)
@SpringBootTest
@ComponentScan
@ImportAutoConfiguration
public class FooTest 

正文完
 0