Mock Stripe API in Laravel with Mockery
Working with 3rd party API’s is always fun, but sometimes it becomes a pain to test your integrations effectively when creating your application
Recently we found ourselves needing something quick and easy to mock some classes in Laravel to test against for expected responses. Usually, given an appropriate budget you’d do something like the following;
- Create an interface — e.g. PaymentGatewayInterface
- Write an implementation for that gateway — e.g. StripePaymentGateway
- Have methods such as “createCharge” in the gateway interface and implement in your Stripe service class
- Create a testing gateway service that returns the expected results — e.g. FakePaymentGateway
- Run your PHPUnit tests against that fake gateway which will return the same data format as your implementation gateway classes
This is covered at length in the great Test Driven Laravel course by Adam Wathan and is definitely the right way to go in a lot of scenarios. However, for a recent client’s MVP, we needed something a little quicker.
Take the following example for creating a customer with Stripe PHP
The stripe account repository
The code here is cut down significantly but the main thing here is seeing a Stripe key being set, and a customer being created in the Stripe account for a specific key.
So how do we go about testing this has the expected response. Well it’s actually pretty simple, in our setup method we new up a mock of the classes we’re going to need to mock and create the classes we need
Our test method
And that’s all there is to it really. Super simple mocks and easy reusability.
Here’s the gist
P.S. a lot of this is cut down for readability, there’s actually a lot more that goes on around these tests but you get the idea. I’d really recommend the Test Driven Laravel course to understand how to effectively test your application.
Originally published at https://lukecurtis.me.