Laravel Cashier testing

fx3z
2 min readSep 26, 2023

--

You’ve done some thinking about it too? Let’s solve this once and for all.

Photo by Elvis Bekmanis on Unsplash

Mock, or not to Mock?

If we are using a library that’s already been tested, isn’t it better to mock it out? This way, tests can be run without an internet connection.

What if there is an update in the API structure, and our offline tests are running successfully? Let’s find out.

Cashier is already being tested, but it’s wise to test features you are using through your application and actually hit the Stripe API. That will gain your confidence that the billing system is working as expected.

Setup

If we follow Laravel documentation, update the phpunit.xml; otherwise you can add a variable to your env.testing, e.g. STRIPE_SECRET.

In the setUp() we need normal user, registered Stripe customer with deafult card and an Stripe Customer object.

setUp()

Test customer can be created, where we create customer with Cashier create customer method and check instance and some random data equality of the response.

test_customer_can_be_created

Test if a customer can be charged, where we try to charge a customer and assert the instance of the response, equality of the rawAmount, and check the stripe_id.

tedst_customer_can_be_charged

And, as a final note, remember to clear all created customers from the Stripe test dashboard to prevent an excessive amount of testing data. This can be achieved using the tearDown method.

tearDown()

What’s your approach and experience on conducting Stripe Cashier tests? dFeel free to share your thoughts and experiences in the comments below. Let’s spark a discussion and learn from each other’s insights!

Cheers.

--

--