Mock Laravel Cashier's checkout method on the Billable trait

48 Views Asked by At

In my API I am getting the checkout url from Stripe using Laravel 11 Cashier 15 and returning it to the front end to redirect the user.

$response = $user->newSubscription($name, $price)
    ->trialUntil(Carbon::now()->addDays(7)->addMinutes(1))
    ->allowPromotionCodes()
    ->checkout([
        'success_url' => $successUrl,
        'cancel_url' => $cancelUrl,
        'consent_collection' => [
            'terms_of_service' => 'required',
        ],
    ]);
    return $response->url;  

The User class is using the Billable trait which uses the PerformsCharges trait which has the checkout method which returns the Checkout class.

I am trying to mock this for a test using PHPUnit 10.

I have tried

$mock = Mockery::mock(User::class)->makePartial();
$mock->shouldReceive('checkout')
    ->andReturn('https://chicken.com');
$mock = Mockery::mock(User::class)->makePartial();
$mock->shouldReceive('allowPromotionCodes->checkout')
    ->andReturn('https://chicken.com');
$mock = Mockery::mock(User::class)->makePartial();
$mock->shouldReceive('newSubscription->trialUntil->allowPromotionCodes->checkout')
    ->andReturn('https://chicken.com');

without any luck. Can anyone see what I am doing wrong? My skills with Mockery are pretty much Google based.

Edit

I have also tried these to no avail.

$subscriptionBuilderMock = Mockery::mock(SubscriptionBuilder::class);

$subscriptionBuilderMock->shouldReceive('trialUntil')
  ->andReturnSelf();

$subscriptionBuilderMock->shouldReceive('allowPromotionCodes')
  ->andReturnSelf();

$checkoutResponse = new stdClass;
$checkoutResponse->url = 'https://chicken.com';

$subscriptionBuilderMock->shouldReceive('checkout')
  ->andReturn($checkoutResponse);

$userMock = Mockery::mock(User::class)->makePartial();

$userMock->shouldReceive('newSubscription')
    ->with($product, $price)
    ->andReturn($subscriptionBuilderMock);

And

$subscriptionBuilderMock = Mockery::mock(SubscriptionBuilder::class);

$subscriptionBuilderMock->shouldReceive('trialUntil->allowPromotionCodes->checkout')
  ->andReturn($checkoutResponse);
  
$userMock = Mockery::mock(User::class)->makePartial();

$userMock->shouldReceive('newSubscription')
    ->with($product, $price)
    ->andReturn($subscriptionBuilderMock);
0

There are 0 best solutions below