问题
写单元测试时,使用@Autowire
注解自动注入一个类
@Autowired
private PrometheusClient prometheusClient;
发现显示错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.eshore.paas.ops.serv.services.common.PrometheusClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
错误信息显示是因为找不到这个bean
导致的。
解决
最后发现是@SpringBootTest
注解中使用的类配置错了,
实际应该写SecondAlertApplication.class
这个类,才会自动扫描该类目录下的所有包。
修改后配置:
@RunWith(SpringRunner.class)
@ActiveProfiles("dev")
//此处修改
@SpringBootTest(classes = SecondAlertApplication.class)
@Transactional
@Rollback
@Slf4j
public class secondAlertTest {
//....代码省略
}
注:
完整的一个单元测试样例: