Ad

Mocking Stripe Class From Stripe Php Package In Laravel

I'm using this package for stripe

https://github.com/stripe/stripe-php

I have a class that I'm using that uses the stripe methods called StripeBiller

class StripeBiller
{

    public function setApiKey() {
        $stripe = new Stripe();
        $stripe->setApiKey(env('STRIPE_API_KEY'));
    }
}

I'm trying to test that the setApiKey method is called when $stripebiller()->setApiKey() is called. To do this I'm mocking the stripe class in the test.

    public function test_api_key_is_set() {

    $this->mock(Stripe::class, function ($mock) {
        $mock->shouldReceive('setApiKey')->once();
    });
    $biller = new StripeBiller();
    $biller->setApiKey();

}

When I execute this test I get this error.

    Mockery\Exception\InvalidCountException : Method setApiKey(<Any Arguments>) from Mockery_2_Stripe_Stripe should be called
 exactly 1 times but called 0 times.

How do I correctly mock this stripe class?

Ad

Answer

You can't mock things you are manually newing up. There are a couple ways to accomplish what you're trying to do here.

  1. Pass a Stripe class into the constructor of your StripeBiller class
class StripeBiller
{
    private $Stripe;

    public function __construct(Stripe $Stripe)
    {
        $this->Stripe = $Stripe;
    }

    public function setApiKey() 
    {
        $this->Stripe->setApiKey(env('STRIPE_API_KEY'));
    }
}
// StripeBillerTest.php
public function test_api_key_is_set()
{
    $StripeMock = \Mockery::mock(Stripe::class);
    $StripeMock->shouldReceive('setApiKey')->once();

    $biller = new StripeBiller($StripeMock);
    $biller->setApiKey();

}

  1. Create the Stripe class with the container and tell the container to use a mock in your test.
// StripeBiller.php
public function setApiKey() 
{
    $stripe = app(Stripe::class);
    $stripe->setApiKey(env('STRIPE_API_KEY'));
}
// StripeBillerTest.php
public function test_api_key_is_set()
{
    $StripeMock = \Mockery::mock(Stripe::class);
    $StripeMock->shouldReceive('setApiKey')->once();
    $this->app->instance(Stripe::class, $StripeMock);

    $biller = new StripeBiller();
    $biller->setApiKey();

}

Ad
source: stackoverflow.com
Ad