springboot 单元测试,测试调用edas中的服务,总是报错,报错原因就是自动注入失败,找不到bean
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'com.edas.hsf.edasservicetest.TestMemberService':
Unsatisfied dependency expressed through field 'memberService';
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.fshows.edas.service.MemberService'
available: expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {@com.alibaba.boot.hsf.annotation.HSFConsumer(serviceVersion=1.0.0, addressWaitTime=3000, proxyStyle=jdk, serviceGroup=myedas, clientTimeout=3000, futureMethods=[], generic=false)}
单元测试类:
@RunWith(PandoraBootRunner.class)
@DelegateTo(SpringJUnit4ClassRunner.class)
// 加载测试需要的类,一定要加入Spring Boot的启动类,其次需要加入本类
@SpringBootTest(classes = { EdasServiceTestApplication.class, IAdminGroupApi.class})
@Component
public class TestMemberService {
@HSFConsumer(serviceGroup = "myedas", serviceVersion = "1.0.0")
private MemberService memberService;
@Test
public void testMember() {
System.out.println("call result: " + memberService.getMember(999999999L));
}
}
不知道啥原因, 后来在该项目中通过controller去调用服务,可以成功调用:
@HSFConsumer(serviceGroup = "lifecircle-service-user-dev", serviceVersion = "1.0.0")
private IAdminGroupApi adminGroupApi;
@HSFConsumer(serviceGroup = "myedas", serviceVersion = "1.0.0")
private MemberService memberService;
@RequestMapping("/my")
public void index(ModelMap map) {
logger.info("=============index===========");
BizResponse<List<AdminGroupDTO>> adminGroupList = adminGroupApi.findAdminGroupList(1);
List<AdminGroupDTO> data = adminGroupList.getData();
System.out.printf(JSON.toJSONString(data));
System.out.println("call result: " + memberService.getMember(88888L));
System.out.println("end");
}
奇怪的是, 再通过单元测试去调用,又可以了
为什么运行单元测试,bean没有注入成功, 自动配置(AutoConfigure)有问题?
奇怪的是:通过controller调用了服务,再运行单元测试就可以了