Magento 2: API Functional Testing

Posted . Visible to the public.

The API funcational testing can be implemented using following steps

First Step : Develop your API

Second Step : Write the API Test class

Eg:

<?php
/**
 * OrganisationRepositoryTest
 *
 * @copyright Copyright © 2023 Vasan. All rights reserved.
 * @author    psureshvasan@yahoo.com
 */

namespace Vasan\Organisation\Test\Api;


use Magento\TestFramework\TestCase\WebapiAbstract;
use Vasan\Organisation\Model\ResourceModel\OrganisationRepository;
use Magento\Customer\Model\ResourceModel\CustomerRepository;
use Magento\TestFramework\Helper\Customer as CustomerHelper;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;

class OrganisationRepositoryTest extends WebapiAbstract
{
    const RESOURCE_PATH = '/V1/vasan/organisation';

    /**
     * @var \Magento\TestFramework\ObjectManager
     */
    protected $objectManager;

    /**
     * @var CustomerHelper
     */
    protected $customerHelper;

    /**
     * @var array
     */
    protected $currentCustomerIds = [];

    /**
     * @var array
     */
    protected $organizationIds = [];

    /**
     * @var array
     */
    protected $tokenCustomerData = [];

    /**
     * @var OrganisationRepository
     */
    protected $organizationRepository;

    /**
     * @var CustomerRepository
     */
    protected $customerRepository;

    /**
     * Execute per test initialization.
     */
    protected function setUp(): void
    {
        $this->objectManager = Bootstrap::getObjectManager();
        $this->customerHelper = new CustomerHelper();
        $this->organizationRepository = $this->objectManager->create(OrganisationRepository::class);
        $this->customerRepository = $this->objectManager->create(CustomerRepository::class);
        $this->tokenCustomerData = $this->_createCustomer();
    }

    /**
     * Testing with default store value.
     *
     * @return void
     * @throws \Magento\Framework\Exception\AuthenticationException
     */
    public function testCreateOrganization()
    {
        $this->_markTestAsRestOnly();

        /** @var CustomerTokenServiceInterface $customerTokenService */
        $customerTokenService = $this->objectManager->create(CustomerTokenServiceInterface::class);
        $orgAdminCustomerData = $this->_createCustomer();

        $token = $customerTokenService->createCustomerAccessToken(
            $this->tokenCustomerData['email'],
            'test@123'
        );


        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
                'token' => $token
            ]
        ];
        $name = 'test' .  uniqid();
        $requestData = ['organisation' => [
            'name' => $name,
            'legal_name' => $name,
            'type' => 11,
            'status' => 1,
            'street' => [
                'tst street', '4'
            ],
            'region_id' => '570',
            'city' => 'Sydney',
            'country_id' => 'AU',
            'postcode' => '3341',
            'telephone' => '4343434333',
            'administrator_id' => $orgAdminCustomerData['id']
        ]];
        $organization = $this->_webApiCall($serviceInfo, $requestData);
        $this->assertNotNull($organization);
        $this->assertNotNull($organization['store_id']);
        $this->assertEquals($organization['name'], $name);
        if (isset($organization)) {
            $this->organizationIds[] = $organization['entity_id'];
        }
    }

    /**
     * Testing with invalid store_code.
     *
     * @return void
     * @throws \Magento\Framework\Exception\AuthenticationException
     */
    public function testCreateOrganizationWithInvalidStoreCode()
    {
        $this->_markTestAsRestOnly();

        /** @var CustomerTokenServiceInterface $customerTokenService */
        $customerTokenService = $this->objectManager->create(CustomerTokenServiceInterface::class);
        $orgAdminCustomerData = $this->_createCustomer();

        $token = $customerTokenService->createCustomerAccessToken(
            $this->tokenCustomerData['email'],
            'test@123'
        );


        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
                'token' => $token
            ]
        ];
        $name = 'test' .  uniqid();
        $requestData = ['organisation' => [
            'name' => $name,
            'legal_name' => $name,
            'type' => 11,
            'status' => 1,
            'street' => [
                'tst street', '4'
            ],
            'store_code' => 'tst',
            'region_id' => '570',
            'city' => 'Sydney',
            'country_id' => 'AU',
            'postcode' => '3341',
            'telephone' => '4343434333',
            'administrator_id' => $orgAdminCustomerData['id']
        ]];
        $organization = [];
        try {
            $organization = $this->_webApiCall($serviceInfo, $requestData);
        } catch (\Exception $exception) {
            $this->assertEmpty($organization);
        }

    }

    /**
     * Testing with valid store_id and invalid store_code.
     *
     * @return void
     * @throws \Magento\Framework\Exception\AuthenticationException
     */
    public function testCreateOrganizationWithStoreId()
    {
        $this->_markTestAsRestOnly();

        /** @var CustomerTokenServiceInterface $customerTokenService */
        $customerTokenService = $this->objectManager->create(CustomerTokenServiceInterface::class);
        $orgAdminCustomerData = $this->_createCustomer();

        $token = $customerTokenService->createCustomerAccessToken(
            $this->tokenCustomerData['email'],
            'test@123'
        );


        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
                'token' => $token
            ]
        ];
        $name = 'test' .  uniqid();
        $requestData = ['organisation' => [
            'name' => $name,
            'legal_name' => $name,
            'type' => 11,
            'status' => 1,
            'street' => [
                'tst street', '4'
            ],
            'store_id' => 1,
            'store_code' => 'tst',
            'region_id' => '570',
            'city' => 'Sydney',
            'country_id' => 'AU',
            'postcode' => '3341',
            'telephone' => '4343434333',
            'administrator_id' => $orgAdminCustomerData['id']
        ]];
        $organization = $this->_webApiCall($serviceInfo, $requestData);
        $this->assertNotNull($organization);
        $this->assertEquals( 1, $organization['store_id']);
        $this->assertEquals($organization['name'], $name);
        if (isset($organization)) {
            $this->organizationIds[] = $organization['entity_id'];
        }
    }

    /**
     * Clear temporary data
     */
    protected function tearDown(): void
    {
        $registry = $this->objectManager->get(Registry::class);
        $registry->unregister('isSecureArea');
        $registry->register('isSecureArea', true);

        foreach ($this->organizationIds as $organizationId) {
            $this->organizationRepository->deleteById($organizationId);
        }

        foreach ($this->currentCustomerIds as $customerId) {
            $this->customerRepository->deleteById($customerId);
        }

        $registry->unregister('isSecureArea');
        $registry->register('isSecureArea', false);
    }

    /**
     * @param array|null $additionalData
     * @return array|bool|float|int|string
     */
    protected function _createCustomer(?array $additionalData = [])
    {
        $customerData = $this->customerHelper->createSampleCustomer($additionalData);
        $this->currentCustomerIds[] = $customerData['id'];
        return $customerData;
    }
}

Last step
Test the test cases
php vendor/bin/phpunit -c $(pwd)/dev/tests/api-functional/phpunit_rest.xml.dist app/code/Vasan/Organisation/Test/

vasan
Last edit
vasan
Keywords
API, Test
Posted by vasan to vasan's deck (2023-03-02 14:06)