Java, 原创,

Spring Boot单元测试Junit 提示expected at least 1 bean which qualifies as autowire candidate

测试代码如下:

@RunWith(SpringRunner.class)
public class BaiduTest {

    @Autowired
    private BaiduService baiduService;

    @Test
    public void testBaiduSearch() {
    }
}

运行代码报如下错误:

Error creating bean with name 'xxx.BaiduTest': Unsatisfied dependency expressed through field 'baiduService';

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'xxx.service.BaiduService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

解决方法:

添加注解:

@SpringBootTest(classes = TestApplication.class)
@RunWith(SpringRunner.class)

@SpringBootTest(classes = TestApplication.class)
public class BaiduTest {

    @Autowired
    private BaiduService baiduService;

    @Test
    public void testBaiduSearch() {
    }
}

TestApplication代码如下:

@SpringBootApplication(scanBasePackages = "xx")
//@EnableFeignClients
@ComponentScan("xxx")
public class TestApplication {
    public static void main(String[] args) {
        //这里填的是TestApplication
        ApplicationContext context = SpringApplication.run(TestApplication.class, args);
    }
}

如此,问题解决。

(1997)

Related Post