Mockito.when.thenReturn未返回预期值(Mockito.when空指针异常)

在这里插入图片描述

下面代码块里这一段里就是说去调用bandwidthAllocationRuleService.listBandwidthAllocationRule方法的时候直接引用我定义好的ipage,但是我这么写,图一的那个allocationRecords一直是个空,我就很纳闷。然后我排查是什么原因,网上看到一篇博文说是因为对象引用的地址不一致或者参数不一致导致的,但是看着有点懵,有兴趣的可以看一下
https://blog.csdn.net/besto229/article/details/106077901/

我下面这个代码中,
regionId是String类型
resourceGroupId是String类型
bandwidthMock是一个自定义的对象,内部有很多属性
10,1这两个是 long 类型的

Mockito.when(bandwidthAllocationRuleService.listBandwidthAllocationRule(regionId,resourceGroupId,bandwidthMock,10,1)).thenReturn(iPage);
        CommonResponse cr = describeBandwidthAllocationRulesAction.processRequest();

所以问题就是出在这个自定义的bandwidthMock对象上,我最后的解决方法是,把String的都改成Mockito.eq(),对象的直接用Mockito.any(XXX.class),
基本数据类型的,直接用Mockito.anyLong()这种,就可以解决了

Mockito.when(bandwidthAllocationRuleService.listBandwidthAllocationRule(Mockito.eq(regionId), Mockito.eq(resourceGroupId)
                , Mockito.any(BandwidthAllocationRule.class), Mockito.anyLong(), Mockito.anyLong())).thenReturn(iPage);
        CommonResponse cr = describeBandwidthAllocationRulesAction.processRequest();
  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
好的,下面是一个Mockito.when()的使用示例。 假设我们有一个名为`Calculator`的类,它有一个`add`方法,用于将两个数字相加。我们想要测试一个使用`Calculator`类的其他类,但是由于我们不想真正调用`add`方法,因此我们可以使用Mockito来模拟`add`方法的行为。 首先,我们需要创建一个`Calculator`类的mock对象,可以使用以下代码: ```java Calculator calculator = Mockito.mock(Calculator.class); ``` 接下来,我们可以使用`when`方法来指定当调用`add`方法时应该返回什么。例如,我们可以指定当`add`方法的参数为2和3时,应该返回5,如下所示: ```java Mockito.when(calculator.add(2, 3)).thenReturn(5); ``` 现在,当我们在测试中调用`calculator.add(2, 3)`时,它将返回5,而不是实际执行`add`方法。这使我们能够测试我们的代码,而不会受到`add`方法的影响。 完整的示例代码如下: ```java import static org.junit.Assert.assertEquals; import org.junit.Test; import org.mockito.Mockito; public class CalculatorTest { @Test public void testAdd() { Calculator calculator = Mockito.mock(Calculator.class); Mockito.when(calculator.add(2, 3)).thenReturn(5); assertEquals(5, calculator.add(2, 3)); } } ``` 在这个测试中,我们创建了一个`Calculator`类的mock对象,并使用`when`方法指定了`add`方法的行为。然后,我们调用`assertEquals`方法来验证`add`方法返回了我们预期的结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iRayCheung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值