mardi 14 mai 2019

Trying to get into testing with PHP, don't know how to handle 3rd party API

Right now I'm developing new module, which will be heavily dependent on 3rd party API. I'm new to testing PHP applications, so I need help with code organization and mocking classes.

I have this file structure:

-exceptions
--BadApiCallException
--ApiError
--...
-requests
--BaseApiRequestClass
--RequestForEntityA
--...
-responses
--BaseApiResponseClass
--EntityA

ApiServiceClass

ApiServiceClass look like this

class ApiService
{
    //Will be Guzzle for production.
    private $transportService;
    private $endPointUrl;

    public static function build($transportService, string $endPointUrl)
    {
        $service = new self();
        $service->transportService = $transportService;
        $service->endPointUrl = $endPointUrl;

        return $service;
    }

    public function getData(BaseApiRequest $request)
    {
        try {
            $response = $this->transportService->get(
                $this->endPointUrl . '/' . $request->getMethod(),
                [
                    'query' => $request->getApiFields()
                ]
            )->send();
        } catch (\Exception $ex) {
            throw new BadApiCallException($ex->getMessage(), $ex->getCode(), $ex);
        }

        if (!$response->isOk) {
            throw new BadApiCallException(
                BadApiCallException::API_RESPONSE_IS_BAD_CODE,
                BadApiCallException::API_RESPONSE_IS_BAD_MESSAGE,
                null,
                $response
            );
        }

        $responseData = json_decode($response->getBody(), true);

        //Api returns it own error
        if (isset($responseData['errorCode'])) {
            throw new ApiErrorException($response->data['errorCode'], $response->data['errorDescription']);
        }

        return $responseData;
    }

    public function getEnetityA(RequestForEntityA $request)
    {
        return EntityA::build($this->getData($request));
    }
}

Will this code be mockable? Is so, how to propery mock and test it.

Aucun commentaire:

Enregistrer un commentaire