注:仅提供思路,具体实现请根据所处环境自行处理
环境:
- jdk8
- Junit4
- springboot 2.3.10.RELEASE
- 导入依赖
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.12.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.6</version>
</dependency>
dubbo rpc服务导入改造
- 原来方式:
直接在需要使用rpc服务的service实现类中使用**@Autowired**进行依赖注入 - 现有方式:
- 新建rpc服务统一管理类
@Configuration
@Getter
public class ConsumerUtil {
@DubboReference(version = "${rpc.user.version}",group = "${rpc.user.group}")
public UserRpcService userRpcService;
@DubboReference(version = "${rpc.order.version}",group = "${rpc.order.group}")
public OrderRpcService orderRpcService;
@DubboReference(version = "${rpc.address.version}",group = "${rpc.address.group}")
public AddressRpcService addressRpcService;
}
- 改造调用rpc服务的service实现类
// 以前的方式:
@Autowired
private UserRpcService userRpcService;
// 现在的方式:
@Autowired
private ConsumerUtil consumerUtil;
// 代码中使用改造:consumerUtil.getUserRpcService()
- 单测改造
@MockBean
private UserRpcService userRpcService;
@MockBean
private ConsumerUtil consumerUtil;
@Before
public void init(){
// mock rpc
Mockito.when(consumerUtil.getUserRpcService()).thenReturn(userRpcService);
}
// 单测方法中使用
@Test
public void test() {
User user = new User();
user.setUserId(1L);
user.setUserName("Jimy");
when(userRpcService.listUser(any(UserListQry.class))).thenReturn(CollUtil.newArrayList(user));
}