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 new
ing up. There are a couple ways to accomplish what you're trying to do here.
- Pass a
Stripe
class into the constructor of yourStripeBiller
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();
}
- 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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad