前言
由于使用SpringBoot运行Junit4测试的方式无法完整的运行Dubbo完整的调用过程(如过滤器失效),且启动速度较慢,故使用Dubbo API构建服务消费者调用服务提供者的服务配合Junit4进行单例测试。
使用Spring Boot进行单例测试的方法
主要是通过添加@SpringBootTest和@RunWith(SpringRunner.class)配合@Autowired注解使用Spring的注入功能进行测试。
@SpringBootTest
@RunWith(SpringRunner.class)
public class RoleHierarchyServiceImplTest {
@Autowired
private RoleHierarchyService roleHierarchyService;
@Test
public void createRoleHierarchy() {
System.out.println(roleHierarchyService.createRoleHierarchy());
}
}
使用Dubbo API进行单例测试的方法
使用Dubbo API进行单例测试时,需要使用@Before注解,在进行测试前,先使用Dubbo API构建测试用的服务消费者。为了单例测试的方便,进行单例测试时不通过注册中心进行注册,而是通过点对点直连的方式连接服务提供者进行测试,即下面代码中的reference.setUrl(ProviderUrl)方法。
使用该方式进行Dubbo服务测试不仅能够通过完整的Dubbo服务调用过程,且启动时间较短,平均启动时间为2-3秒。
public class RoleHierarchyServiceImplTest {
private RoleHierarchyService roleHierarchyService;
@Before
public void before() {
ApplicationConfig application = new ApplicationConfig();
application.setName("userServiceTest");
ReferenceConfig<RoleHierarchyService> reference = new ReferenceConfig<>();
reference.setUrl("dubbo://127.0.0.1:20881/com.xiaohuashifu.recruit.user.api.service.RoleHierarchyService");
reference.setApplication(application);
reference.setInterface(RoleHierarchyService.class);
roleHierarchyService = reference.get();
}
@Test
public void createRoleHierarchy() {
System.out.println(roleHierarchyService.createRoleHierarchy());
}
}