Summer Sale! All accounts are 50% off this week.

nateritter's avatar

How to TDD/BDD by Mocking External APIs

I can't seem to find a way to do TDD/BDD with external APIs in PHP, none-the-less Laravel. It would be great is there was a PHP package similar to WireMock (ref: http://wiremock.org/ ). Most alternative seem to be out of date (dependencies or the lib itself).

Ideally, I'd love to see a video on how to do this easily and properly.

For now I'm going to try https://github.com/InterNations/http-mock , but I'd love to hear any other suggestions/alternatives out there.

UPDATE: I did also just find https://github.com/aerisweather/GuzzleHttpMock which seems to be promising considering I've used the Guzzle libraries in the past.

0 likes
5 replies
RaulEBC's avatar

Do you know if this class belongs to a series?

rikh's avatar

I use AspectMock (https://github.com/Codeception/AspectMock) to mock out the API wrappers in my projects, so I can test all the possible error conditions from an external API as well as what happens when things are going well. For example...

        // Mock the stripe API
        $apiMock = test::double(StripeApiWrapper::class, [
            'createCustomer' => [
                'id' => 'TestStripeId',
                'subscription' => 'TestSubscription',
                'cardBrand' => 'VisaTest',
                'lastFour' => '1234',
            ]
        ]);

I can then perform a normal functional test in Laravel, and when it gets to calling Stripe, it will instead return that array and I can test that the users account has been updated to the correct state.

1 like
mick_ronson's avatar

Hi I'm trying to use AspectMock with the 'httpful' library.. my attempt so far is...

        $apiMock = test::double(\Httpful\Request::class, [
            'get' => [
                'some' => 'sample data'
            ]
        ]);

I'm getting ' Call to a member function registerClass() on a non-object '. I'm obviously phrasing the reference to httpful's request class wrong, but I'm also unsure whether what I'm trying to do is even possible.

Please or to participate in this conversation.