springboot单测如何mock掉rpc服务

注:仅提供思路,具体实现请根据所处环境自行处理

环境:

  1. jdk8
  2. Junit4
  3. springboot 2.3.10.RELEASE
  4. 导入依赖
		<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服务导入改造

  1. 原来方式:
    直接在需要使用rpc服务的service实现类中使用**@Autowired**进行依赖注入
  2. 现有方式:
  • 新建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));
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值