关于mockito如何返回代码中实际生成的值

业务背景

购买某些商品 会发一些优惠券 如1张满100减50元美甲券、1张满100减50元美发券

先根据优惠券描述(如100_50_mei_jia)判断对应的优惠券模板是否存在

couponCodeList = redisService.hmget(key,"100_50_mei_jia","100_50_mei_fa")

如果不存在(即返回值为NULL) 去创建

UUIDGenerator.getUUID32(); // 生成优惠券couponCode

然后将新创建的优惠券编码(coupon_code)保存在redis hash中

redisService.hmset(key, ImmutableMap.of("100_50_mei_jia","2aa833d9828a4d0681c02e5f94d52724","100_50_mei_fa","719e984701264fa8bb5a3d979df37771"));

最后再次查询redis hash key 得到所有的couponCode
基于这些couponCode批量给用户发券

couponCodeList = redisService.hmget(key,"100_50_mei_jia","100_50_mei_fa");
// 需要基于这些couponCode 得到Map<优惠券编码, 发放张数>
couponService.batchAddUserCoupons(userId,couponCodeCountMap );

代码中有两次查询hash key 因为模拟全部需要新建优惠券模板 故第一次只要返回全部为空即可

when(redisService.hmget(key,newHashSet(couponDescList).toArray(new String[]{}))).thenReturn(Lists.<String>newArrayList(null,null));

但是第二次要返回代码中实际生成的couponCode(UUIDGenerator.getUUID32();)如何处理呢?

when(redisService.hmget(key,newHashSet(couponDescList).toArray(new String[]{}))).thenReturn(Lists.<String>newArrayList(null,null)).thenReturn(?,?);

即如何返回代码中实际生成的值呢?便于后面验证batchAddUserCoupons中捕捉的参数couponCodeCountMap

阅读 4.1k
2 个回答

看这个:http://site.mockito.org/mocki...

when(mock.someMethod(anyString())).thenAnswer(new Answer() {
     Object answer(InvocationOnMock invocation) {
         Object[] args = invocation.getArguments();
         Object mock = invocation.getMock();
         return "called with arguments: " + args;
     }
 });

 //the following prints "called with arguments: foo"
 System.out.println(mock.someMethod("foo"));

你可以在Answer里放一个Map就行了

宣传栏