Back

Testing Stripe - How can I mock the Services?


felipegarcia92 posted 3 years ago

Hello guys,

I'm using phpunit 4.0.17 and I'm using stripe for subscriptions on my website. I want to test the Stripe controller I have, but for that, I don't want to depend on Stripe's API, not even using their test keys because that'll slow down the testing process, plus depends on the API itself.

For example, there's this Stripe_Customer class, whose 'create' method I call in a Repository with all of the Stripe's calls to get the creation of a Customer done. Now, that brings a response and I want to test that my controller (which uses that Repository) is handling all of the responses well, without depending on the things mentioned above.

Do you know any way that I could mock Stripe_Customer::create(), for example?

This is in my controller:

function __construct(PaymentRepositoryInterface $payments)
{
    $this->payments = $payments;
    parent::__construct();
}

public function create_customer($token) {
    $currentUser = Auth::user();

    // Create Customer with Credit Card token provided by Stripe.js on Stripe's end
    $customer = $this->payments->createCustomer(array(
      'email' => $currentUser['email'],
      'user_id' => $currentUser['id'],
      'token' => $token
    ));

    // Save customer and other stuff
}

This is in my StripeRepository which implements PaymentRepositoryInterface

public function createCustomer($data){
	try {
		$customer = array(
			'email'=> $data['email'],
			'source' => $data['token']
		);
		$response = \Stripe_Customer::create($customer);
		return $response;
	} catch (Exception $e) {
		Log::error('Exception occured creating a customer in Stripe.', ['exception'=>$e]);
	}
}

And in my Unit test I want to be able to call the controller or at least the repository method, but with Stripe_Customer::create(..) returning something I can mock.

Thanks in advance! Felipe


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us