You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel下使用Mockery模拟Stripe API链式调用retrieve方法失败如何解决

错误根因

你的模拟逻辑存在两个问题:

  • 手动将customers属性赋值为空字符串,导致调用retrieve()方法时触发字符串调用成员方法的错误
  • 把retrieve()方法的调用预期绑定到了Stripe根对象上,实际业务代码中该方法是customers属性对应实例的成员方法

正确模拟方案

方案1:单独模拟Customer服务实例(可读性更高)

Stripe SDK中customers属性对应Stripe\Service\CustomerService类的实例,你需要先模拟这个服务类,再把它赋值给Stripe根mock对象的customers属性:

// 模拟Customer服务对象
$customerServiceMock = Mockery::mock(\Stripe\Service\CustomerService::class);
$customerServiceMock->shouldReceive('retrieve')
    ->once()
    ->andReturn([]); // 这里可以替换为你需要的模拟customer数据

// 模拟Stripe根对象
$stripeMock = Mockery::mock(\Stripe\StripeClient::class);
$stripeMock->shouldReceive('setApiKey')->once();
// 绑定customers属性到模拟的服务实例
$stripeMock->customers = $customerServiceMock;

方案2:使用Mockery链式调用模拟(写法更简洁)

Mockery原生支持多级链式方法调用的模拟,无需手动创建子属性的mock实例:

$stripeMock = Mockery::mock(\Stripe\StripeClient::class);
$stripeMock->shouldReceive('setApiKey')->once();
// 直接模拟customers->retrieve的链式调用
$stripeMock->shouldReceive('customers->retrieve')
    ->once()
    ->with($event->item->stripe_id) // 可加参数校验,不需要可以删除
    ->andReturn([]);

两种方案都可以正常匹配业务代码中的调用逻辑,运行测试不会再报属性未定义或方法调用错误。


内容的提问来源于stack exchange,提问作者Lewis Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 21:42:01